Wait (), notify (), Notifyall () Understanding and use

Source: Internet
Author: User

These three methods, because of the need to control control over the object (monitor), belong to object and not to the thread.

Wait () will hand over the object control that holds the object's thread and wait.

Notify () notifies a thread that is waiting for control of this object to continue running.

Nofifyall () Notifies all threads waiting for control of this object to continue running, which is dispatched by the operating system if there is more than one thread that is waiting for control of the object to wake up.

Attention:

1. Producers, consumers must operate on the same resource.

2. Whether you are executing an object's wait, notify, or Notifyall method, you must ensure that the currently running thread has control over the object (monitor)

Producers:

 Packagecom.currentPro.waitAndnotify;Importjava.util.ArrayList;Importjava.util.List; Public classProducerImplementsrunnable{PrivateList<integer> Taskqueue =NewArraylist<integer>(); //Quantity of production    Private Final intmax_capacity;  PublicProducer (list<integer> Sharedqueue,intsize) {         This. Taskqueue =Sharedqueue;  This. Max_capacity =size; } @Override Public voidrun () {intCounter = 1;  while(true)          {             Try             {               synchronized(taskqueue) { while(taskqueue.size () = =max_capacity) {System.out.println (' Queue is full ' + thread.currentthread (). GetName () + "is waiting, size:" +taskqueue.size ());                        Taskqueue.wait (); } thread.sleep (1000);                        Taskqueue.add (counter); System.out.println ("Produced:" +counter); Counter++; //Wake the waiting consumer, but the consumer is not able to get to the resource, dispatched by the system. Taskqueue.notifyall (); }             }              Catch(Interruptedexception ex) {ex.printstacktrace (); }          }       }    }

Consumers:

 Packagecom.currentPro.waitAndnotify;Importjava.util.List; Public classConsumerImplementsrunnable{Private FinalList<integer>Taskqueue;  PublicConsumer (list<integer>sharedqueue) {         This. Taskqueue =Sharedqueue; } @Override Public voidrun () { while(true)          {             Try             {                 synchronized(taskqueue) { while(Taskqueue.isempty ()) {System.out.println (' Queue is empty ' + thread.currentthread (). GetName () + "is waiting, size:" +taskqueue.size ());                        Taskqueue.wait (); } thread.sleep (1000); inti = (Integer) taskqueue.remove (0); System.out.println ("Consumed:" +i);                     Taskqueue.notifyall (); }             } Catch(Interruptedexception ex) {ex.printstacktrace (); }          }       }}

Test code:

 Packagecom.currentPro.waitAndnotify;Importjava.util.ArrayList;Importjava.util.List; Public classTest { Public Static voidMain (string[] args)throwsinterruptedexception {//shared ResourcesList<integer> Taskqueue =NewArraylist<integer>(); intMax_capacity = 5; //Create a producer threadThread producer =NewThread (NewProducer (taskqueue,max_capacity), "Producer"); //Create a consumer threadThread consumer =NewThread (NewConsumer (Taskqueue), "Consumer");        Consumer.start (); Thread.Sleep (2000);            Producer.start (); }}

Resources

http://longdick.iteye.com/blog/453615

http://howtodoinjava.com/core-java/multi-threading/how-to-work-with-wait-notify-and-notifyall-in-java/

Http://www.cnblogs.com/dolphin0520/p/3920385.html

Wait (), notify (), Notifyall () Understanding and use

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.