Classic mode: Producer-Consumer model: When the queue is full, the producer needs to wait for the queue to have space to continue to put the goods inside, and during the waiting period, the producer must release the seizure rights to the critical resource (that is, the queue). Because producers do not release the use of critical resources, consumers will not be able to consume the goods in the queue, there is no space for the queue, then the producers have been waiting indefinitely. Therefore, in general, when the queue is full, the producer will be handed over to the critical resources of the occupation, and into the suspended state. Then wait for the consumer to consume the goods, and then the consumer informs the producer that the queue has space. Similarly, when the queue is empty, the consumer must wait, waiting for the producer to notify it that there is a product in the queue. This process of communicating with each other is a collaboration between threads.
Transfer from http://www.cnblogs.com/dolphin0520/p/3920385.html
A. Wait (), notify (), and Notifyall ()
ImportJava.util.PriorityQueue; Public classQueuetest {Private intQueuesize = 10; Privatepriorityqueue<integer> queue =NewPriorityqueue<integer>(queuesize); Public Static voidMain (string[] args) {queuetest test=Newqueuetest (); Producer Producer= Test.NewProducer (); Consumer Consumer= Test.NewConsumer (); Producer.start (); Consumer.start (); } //////////////////////////////////////////// classProducerextendsThread {@Override Public voidrun () { while(true) { //The Wait () method notify () method must be in a synchronous block or synchronous method (synchronized block or Synchronized method) synchronized(queue) {//Lock when the queue is full while(queue.size () = =queuesize) { Try{System.out.println ("The queue is full, waiting for free space"); //the Wait () method that invokes an object can cause the current thread to block, and the current thread must have a monitor (that is, a lock) on the object.//calling the Wait () method of an object is equivalent to having the current thread hand over the object's monitor and then going into a wait state to wait for subsequent locks on the object.//(The Sleep method in the thread class causes the current thread to suspend execution for a period of time, allowing other threads to continue executing, but it does not release the object lock);queue.wait (); } Catch(interruptedexception e) {e.printstacktrace (); Queue.notify (); }} queue.offer (1);//Insert one element at a time//invoking an object's Notify () method wakes up a thread waiting for the object's monitor, and if more than one thread waits for the object's monitor, only one of the threads can be awakened;//Call the Notifyall () method to wake up all the threads that are waiting for this object's monitor;//The notify () and Notifyall () methods simply wake up the thread that waits for the object's monitor and do not determine which thread can get to monitor. //a thread being awakened does not represent an immediate capture of the object's monitor, but only when the Notify () or Notifyall () is called and exits the synchronized block, the remaining threads can get lock execution after the object lock is released. queue.notify (); System.out.println ("Insert an element into the queue, the remaining space of the queue:" + (Queuesize-queue.size ())); } } } } //////////////////////////////////////////// classConsumerextendsThread {@Override Public voidrun () { while(true) { synchronized(queue) {//queue is an empty-time lock while(queue.size () = = 0) { Try{System.out.println ("Queue empty, waiting for data"); Queue.wait (); } Catch(interruptedexception e) {e.printstacktrace (); Queue.notify (); }} queue.poll (); //Remove the first element of the team every timequeue.notify (); System.out.println ("Take an element from the queue, queue remaining" + queue.size () + "elements"); } } } }}
Two. Condition
Condition is only present in Java 1.5, it is used to replace the traditional object of Wait (), notify () to implement the collaboration between threads, compared to the Wait (), notify () using object, and the Condition1 await () , signal () is a more secure and efficient way to collaborate between threads.
Therefore, it is generally recommended to use the condition, as described in the blocking Queue blog post, where the blocking queue is actually using condition to simulate inter-threading collaboration.
- Condition is an interface, the basic method is the await () and the signal () method;
- Condition relies on the lock interface, generating a condition base code that is Lock.newcondition ()
- The await () and signal () methods that call condition must be within lock protection, meaning they must be between Lock.lock () and Lock.unlock.
Await () in Conditon corresponds to the Wait () of object;
The signal () in condition corresponds to the Notify () of the object;
The Signalall () in condition corresponds to the Notifyall () of the object.
ImportJava.util.PriorityQueue;Importjava.util.concurrent.locks.Condition;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock; Public classTest {Private intQueuesize = 10; Privatepriorityqueue<integer> queue =NewPriorityqueue<integer>(queuesize); PrivateLock lock =NewReentrantlock (); PrivateCondition Notfull =lock.newcondition (); PrivateCondition Notempty =lock.newcondition (); Public Static voidMain (string[] args) {test test=NewTest (); Producer Producer= Test.NewProducer (); Consumer Consumer= Test.NewConsumer (); Producer.start (); Consumer.start (); } classConsumerextendsThread {@Override Public voidrun () { while(true) { //The await () and signal () methods that call condition must be within lock protection, meaning they must be between Lock.lock () and Lock.unlock .Lock.lock (); Try { while(queue.size () = = 0) { Try{System.out.println ("Queue empty, waiting for data"); Notempty.await (); } Catch(interruptedexception e) {e.printstacktrace (); }} queue.poll (); //Remove the first element of the team every timenotfull.signal (); System.out.println ("Take an element from the queue, queue remaining" + queue.size () + "elements"); } finally{lock.unlock (); } } } } classProducerextendsThread {@Override Public voidrun () { while(true) {lock.lock (); Try { while(queue.size () = =queuesize) { Try{System.out.println ("The queue is full, waiting for free space"); Notfull.await (); } Catch(interruptedexception e) {e.printstacktrace (); }} queue.offer (1);//Insert one element at a timenotempty.signal (); System.out.println ("Insert an element into the queue, the remaining space of the queue:" + (Queuesize-queue.size ())); } finally{lock.unlock (); } } } }}
Thread_ inter-thread collaboration: Wait, notify, notifyall, and condition