Chapter 4: Comprehensive combat: "producer - consumer" model

The basic program producers and consumers

In the development process, multi-threaded case is the most famous producers and consumers operate, the main flow of the operation are as follows:

  The producers responsible for the information content production

  Whenever producers to produce after the completion of a complete consumer information from there out information;

  If producers do not generate the consumers who have to wait for it to complete the production, if consumers have not the information the consumer, the producer should wait for processing to complete before continuing to generate consumer

Producers and consumers may be defined as two separate threads class object, but for now the data generated, the following composition

  A Data: title = Wang, content = Big guy;

  Data two: title = small high, content = insignificant a first person;

Since producers and consumers are two separate threads, you need to have saved a focal point for data between two separate threads, you can define a class that implements the data stored separately Message

 

By executing the entire code you will find that at this time there are two main problems:

  One problem: the data is not synchronized;

  Second problem: a removal of a production, but there are problems with repetitive repeat withdrawn

Solve the producer - consumer synchronization problem (to solve the data synchronization)

 First address data synchronization, the easiest way is to use synchronized keyword, or a block synchronization code synchronization method, so this time can be done directly in the Message class for handling synchronization.

 

 When performing the synchronization process certainly requires a synchronous processing target, then you want to be sure this time synchronization operations referred Message handling is the most appropriate. This time data has been found to be consistent, but to repeat the problem still exists. That synchronization can not solve the problem of duplicate operations.

 

 

 

Repeat using the Object class to solve the problem

Guess you like

Origin www.cnblogs.com/djlindex/p/11225345.html