Turn: Java concurrency Programming 13: Producer-consumer model (with code)

Source: Internet
Author: User

Reprint Please specify source:http://blog.csdn.net/ns_code/article/details/17249321

Producer-consumer issues are a classic problem in threading models: producers and consumers share the same storage space during the same time period, producers produce data in space, and consumers take data.

Here are the production-consumption models for the following scenarios:

    Producers are alternately producing two sets of data "name--1-and content--1", " name--2--> content--2", consumers are constantly alternately access to these two sets of data, where the " name--1" and " name--2" simulation is the name of the data, "content--1" and "Content--2" The content of the simulation for the data.

due to the uncertainty involved in threading the program, the following issues may occur:

1, assuming that the producer Line Cheng gang to the data storage space to add the name of the data, has not been added to the content of the information, the program switched to the consumer thread, the consumer thread will be the name of the information and the content of the previous information to link together;

2, the producer produces several times the data, the consumer only then starts to take the data, or is, after the consumer has completed once the data, has not waited for the producer to put in the new data, but also repeated took out the data which has been taken.

Problem 1 is obviously to be solved by synchronization, problem 2 requires inter-thread communication, the producer thread puts the data, notifies the consumer thread to take out the data, the consumer thread takes out the data, notifies the producer thread production data, which is implemented by the wait/notify mechanism.

The detailed implementation code is as follows:

[Java]View PlainCopy
  1. Class info{ //Defining information Classes
  2. private String name = "name"; Define the Name property, in order to distinguish it from the Name property of the following set
  3. private String content = "Content"; Defines the content property in order to distinguish it from the content property of the following set
  4. Private Boolean flag = true; //Set flag bit, first production at initial
  5. public synchronized Void set (String name,string content) {
  6. While (!flag) {
  7. try{
  8. super.wait ();
  9. }catch (Interruptedexception e) {
  10. E.printstacktrace ();
  11. }
  12. }
  13. this.setname (name); //Set name
  14. try{
  15. Thread.Sleep (300);
  16. }catch (Interruptedexception e) {
  17. E.printstacktrace ();
  18. }
  19. this.setcontent (content); //Set content
  20. Flag = false; //Change the flag to indicate that it can be taken away
  21. super.notify ();
  22. }
  23. public synchronized Void Get () {
  24. While (flag) {
  25. try{
  26. super.wait ();
  27. }catch (Interruptedexception e) {
  28. E.printstacktrace ();
  29. }
  30. }
  31. try{
  32. Thread.Sleep (300);
  33. }catch (Interruptedexception e) {
  34. E.printstacktrace ();
  35. }
  36. System.out.println (this.getname () +
  37. " --" + this.getcontent ());
  38. Flag = true; //Change the flag to indicate that it can be produced
  39. super.notify ();
  40. }
  41. public void SetName (String name) {
  42. this.name = name;
  43. }
  44. public void SetContent (String content) {
  45. this.content = content;
  46. }
  47. Public String GetName () {
  48. return this.name;
  49. }
  50. Public String getcontent () {
  51. return this.content;
  52. }
  53. }
  54. Class Producer implements runnable{ //multi-threaded via Runnable
  55. Private Info info = null; //Save Info Reference
  56. Public Producer (info info) {
  57. this.info = info;
  58. }
  59. public Void Run () {
  60. Boolean flag = true; //define marker bit
  61. For (int i=0;i<10;i++) {
  62. if (flag) {
  63. This.info.set ("name--1","content--1"); //Set name
  64. Flag = false;
  65. }else{
  66. This.info.set ("name--2","content--2"); //Set name
  67. Flag = true;
  68. }
  69. }
  70. }
  71. }
  72. Class Consumer implements runnable{
  73. Private Info info = null;
  74. Public Consumer (info info) {
  75. this.info = info;
  76. }
  77. public Void Run () {
  78. For (int i=0;i<10;i++) {
  79. This.info.get ();
  80. }
  81. }
  82. }
  83. Public class threadcasedemo03{
  84. public static void Main (String args[]) {
  85. Info info = new info (); //Instantiate info object
  86. Producer Pro = new Producer (info); //producer
  87. Consumer con = new Consumer (info); //Consumer
  88. new Thread (PRO). Start ();
  89. //starts the producer thread and then starts the consumer thread
  90. try{
  91. Thread.Sleep (500);
  92. }catch (Interruptedexception e) {
  93. E.printstacktrace ();
  94. }
  95. new Thread (Con). Start ();
  96. }
  97. }


The results of the implementation are as follows:

In addition, in the Run method, the number of cycles is the same, otherwise, when one side of the loop ends, the other side of the loop continues, it will block at the wait () method, and wait for the other party's notify notification.

Turn: Java concurrency Programming 13: Producer-consumer model (with code)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.