Java Threading: Concurrent collaboration-producer consumer models

Source: Internet
Author: User

For multi-threaded programs, the producer consumer model is the most classic, regardless of any programming language.
In fact, it should be the "producer-consumer-warehousing" model, which leaves the warehouse, and the producer-consumer model seems unconvincing.
For this model, the following points should be clarified:

    1. Producers are only produced when the storage is not full, and the production is stopped when the warehouse is full.
    2. Consumers can only consume when the goods are in storage and Cang wait.
    3. When consumers find that there is no product in storage, they will inform the producer.
    4. When producers produce consumable products, they should inform consumers to consume.

This model will be combined with Java.lang.Object's wait and Notify,notifyall methods to achieve the above requirements. This is very important.
Implemented in code as follows:

Class godown{ Public StaticFinalintMax_size = -;//Maximum stock volume     Public intCurnum;//Current Stock quantity     Public Godown() {//TODO auto-generated constructor stub} Public Godown(intCurnum) { This. curnum = Curnum; } PublicSynchronizedvoid Produce(intNeednum) {//production of a specified number of products         while((neednum+curnum) >max_size) {//Detect if production is requiredSystem. out. println ("Quantity of products to be produced"+neednum+"Excess inventory exceeded"+ (Max_size-curnum) +", production task 1 cannot be performed temporarily .);Try{//Current line-of-process waitingWait (); }Catch(Interruptedexception e)             {E.printstacktrace (); }        }//Meet production conditions, then make production, change current stock quantityCurnum + = Neednum; System. out. println ("already produced."+neednum+"A product, the current storage capacity is"+curnum);//Wake up all threads waiting on this object monitorNotifyall (); } PublicSynchronizedvoid Consume(intNeednum) { while((Curnum<neednum)) {//Detect if it can be consumed            Try{//Current line-of-process waitingWait (); }Catch(Interruptedexception e)            {E.printstacktrace (); }        }//Meet consumption conditions, then consume, i.e. change the current inventory amountCurnum-= Neednum; System. out. println ("already consumed."+neednum+"A product, the current storage capacity is"+curnum);//Wake up all threads waiting on this monitorNotifyall (); }}
/ * producer * / class Producer extends Thread{    Private intNeednum;//number of products produced    PrivateGodown Godown;//Warehouse     PublicProducer (intNeednum,godown Godown) {//TODO auto-generated constructor stub         This. neednum = Neednum; This. Godown = Godown; } Public voidRun () {//production of a specified number of productsGodown.produce (Neednum); }}
/ * Consumer * / class Consumer extends Thread{    Private intNeednum;//number of products produced    PrivateGodown Godown;//Warehouse     PublicConsumer (intNeedrum,godown Godown) {//TODO auto-generated constructor stub         This. neednum = Needrum; This. Godown = Godown; } Public voidRun () {//consumption of a specified number of productsGodown.consume (Neednum); }}

Main program Implementation code:

 PackageCom.leetch.Threads;Importjava.lang.*; Public  class Test {     Public Static void Main(String args[]) {Godown Godown =NewGodown ( -); Consumer C1 =NewConsumer ( -, Godown); Consumer C2 =NewConsumer ( -, Godown); Consumer C3 =NewConsumer ( -, Godown); Producer P1 =NewProducer (Ten, Godown); Producer P2 =NewProducer (Ten, Godown); Producer P3 =NewProducer (Ten, Godown); Producer P4 =NewProducer (Ten, Godown); Producer P5 =NewProducer (Ten, Godown); Producer P6 =NewProducer (Ten, Godown);        C1.start ();        C2.start ();        C3.start ();        P1.start ();        P2.start ();        P3.start ();        P4.start ();        P5.start ();    P6.start (); }}

The results of one execution are as follows:

Description:
For this example, to show that when a production or consumption condition is not met, call the object's Wait () method, the function of the wait method is to release the lock obtained by the current thread, and call the object's Notifyall () method, notify (Wake) the other waiting thread on the object, so as to continue execution. In this way, the entire producer, the consumer thread can be executed correctly.
The Nitifyall () method, which acts as a notification function, does not release the lock, nor acquires the lock, just tells the waiting thread on the object to "compete for execution, all to execute!" ”。
In this case, if the consumer consumption of storage is not satisfied, and there is no producer, then the process will be in a waiting state, which of course is not correct, in fact, can be modified to modify the production according to consumption, while the production of a warehouse, if the storehouse is not satisfied with the production, and the maximum consumption of each limit, This does not exist, of course, and the example is more complicated.
Java Threads: Concurrent collaboration-Deadlock
The likelihood of a thread deadlock is small, even if the code that appears to be a deadlock may occur, the likelihood of a deadlock at run time is small.
The cause of a deadlock is generally caused by the locking of two objects waiting for each other.
For example:

 Public classTest { Public Static void Main(string[] args) {Deadlockrisk Dead =NewDeadlockrisk (); MyThread T1 =NewMyThread (Dead,1,2); MyThread t2 =NewMyThread (Dead,3,4); MyThread t3 =NewMyThread (Dead,5,6); MyThread T4 =NewMyThread (Dead,7,8);                 T1.start ();                 T2.start ();                 T3.start ();         T4.start (); }} class MyThread extends Thread {PrivateDeadlockrisk dead;Private intA, B; MyThread (Deadlockrisk dead,intAintb) { This. Dead = dead; This. A = A; This. B = b; } @Override Public void Run() {dead.read ();         Dead.write (A, b); }} class Deadlockrisk {Private Static classResource { Public int value; }PrivateResource Resourcea =NewResource ();PrivateResource RESOURCEB =NewResource (); Public int Read() {synchronized (resourcea) {System. out. println ("read ():"+ Thread.CurrentThread (). GetName () +"Get the lock of Resourcea!" "); Synchronized (RESOURCEB) {System. out. println ("read ():"+ Thread.CurrentThread (). GetName () +"Get the lock of RESOURCEB!" ");returnResourceb.value+ Resourcea.value; }                 }         } Public void Write(intAintb) {synchronized (RESOURCEB) {System. out. println ("Write ():"+ Thread.CurrentThread (). GetName () +"Get the lock of Resourcea!" "); Synchronized (resourcea) {System. out. println ("Write ():"+ Thread.CurrentThread (). GetName () +"Get the lock of RESOURCEB!" "); Resourcea.value= A; Resourceb.value= b; }                 }         } }

Java Threading: Concurrent collaboration-producer consumer models

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.