In front of the thread synchronization problem, synchronization problem is mainly to ensure that the concurrent access to the shared resources will not be wrong, the main idea is to let only one thread to access the shared resources, we are implemented by means of locking. But sometimes we also need to schedule a few threads, and the internal thread of the system is scheduled to be transparent, and there is no way to control the switching of threads accurately. So Java provides a mechanism to ensure the coordinated operation between threads, which is what we call thread scheduling. We'll cover three ways to use thread communication below, and each will be tested with producer consumer issues.
One. Using the thread communication mechanism provided by the object class
The object class provides wait (), notify (), and Notifyall () three methods for thread communication. These three methods must be called by the synchronization monitor object, which is divided into the following two cases:
1) for synchronous methods that use the synchronized adornment, because the default instance (this) of the class is the synchronization monitor, you can call these three methods directly in the synchronous method.
2) for a synchronous block of code that uses synchronized adornments, the synchronization monitor is the object in parentheses after synchronized, so you must use that object to call these three methods.
In other words, these three methods can only be used for synchronized to do synchronous thread communication. The specific explanations for the three methods are as follows:
Wait (): Causes the current thread to wait until another thread calls the synchronization Monitor's notify () or Notifyall () method to wake the thread. The wait () method can also pass in a time parameter, which wakes up automatically when the specified time is reached. The current thread that calls the wait () method releases the lock on the synchronization monitor.
Notify (): Wakes up a single thread waiting on this synchronization monitor. If more than one thread is currently waiting, select one randomly. Note the wake-up thread can only be executed if the front-thread discards the lock on the synchronization monitor (using the Wait () method).
Notifyall (): Wakes up all the threads waiting on this synchronization monitor. It is also possible to execute a wake-up thread only after the current thread abandons the lock on the synchronization monitor.
Producer consumer problems modeled using this communication mechanism are as follows:
Package lkl1;/// the corresponding buffer in producer consumers//Producers can add data to the buffer and consumers can consume the data in the buffer//Note that the buffer is limited in size, so use the idea of a cyclic queue to simulate Public classBuffer {//Based on the thought of the cyclic queue, if out==in, the current buffer is empty and cannot be consumed //if (in+1)%n==out, indicates that the current buffer is full and cannot be produced (this will waste a space) Private intN// buffer size Private intNum//Current number of elements //define a buffer of size n Private intBuffer[];//Represents the location where data is currently available, initially 0 Private int inch=0;//Indicates the current location where data can be read, initially 0 Private int out=0; Buffer (intN) { This. n=n; Buffer=New int[n]; num=0; }//Below is the method of production and consumption //production operations, adding an element x to a buffer PublicSynchronizedvoid Product(intx) {Try{if((inch+1)%n== out) {wait ();//If the buffer is full, the current thread is blocked}Else{buffer[inch]=x;inch=(inch+1)%n; System. out. println (Thread.CurrentThread (). GetName () +"Production of an element:"+X); num++; System. out. println ("The current number of elements is:"+num); Notifyall ();//Wake up the thread waiting for the current synchronization Resource Monitor} }Catch(Interruptedexception ex) {Ex.printstacktrace (); } }/// consumption operation, one element at a time PublicSynchronizedvoid Comsumer(){Try{if(inch== out){//If the buffer is empty, the current thread is blockedWait (); }Else{intxx=buffer[ out]; out=( out+1)%n; num--; System. out. println (Thread.CurrentThread (). GetName () +"Consumed an element:"+XX); System. out. println ("The current number of elements is:"+num); Notifyall (); } }Catch(Interruptedexception ex) {Ex.printstacktrace (); } }}
PackageLKL1;ImportJava.util.Random;//Producer Threads//will continue to add elements to the buffer Public class Product extends Thread{ //When the buffer object for the front-thread operation PrivateBuffer buffer;PrivateRandom Rand; Product () {} product (buffer buffer) { This. Buffer=buffer; Rand=NewRandom (); } Public void Run(){ while(true){//Add a random number to the bufferBuffer.product (Rand.nextint ( -)); } }}
package lkl1;//producer thread public class consumer extends thread { private buffer buffer; Consumer () {} Consumer (buffer buffer) {this . Buffer=buffer; } public void run () {while (true ) {//consumes one element of the buffer each time buffer.comsumer (); } }}
package lkl1; Test public class buffertest {public static void main (string[] args) {Buffer buffer = new Buffer (10 ); //a producer, multiple consumers new Product (buffer). Start (); new Consumer (buffer). Start (); new Consumer (buffer). Start (); }}
Two. Using condition to control thread communication
Before we talked about synchronization, in addition to the Synchronized keyword, we also talked about the locking that can be displayed with lock. There is no implicit synchronization monitor when using the lock object, so it is not possible to use the above thread communication mode. In fact, when using the lock object to ensure synchronization, Java provides a condition class to maintain coordination, using the condition class to release the lock object for those threads that have already obtained the lock object but cannot continue.
Condition provides three methods: await (), signal (), Signallall (), and the basic usage of the three methods of the three methods and object objects is the same. In fact, we can say that the lock object corresponds to the synchronization method or the synchronization code block we talked about above, and the condition object corresponds to the synchronization monitor we talked about above. Also note that the condition instance is bound to a lock object, and to obtain the condition instance of the specified lock, the Newcondtion () method of the lock object needs to be called.
The following combination of lock and condition is used to implement producer consumer issues. You can see that the code is basically the same as above.
Package Lkl1;import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.ReentrantLock;/// buffer in producer consumers//represented by an array, the producer can add elements to the buffer, and the consumer can take the element away from the buffer//If the buffer is full, the producer cannot add elements to the buffer, and if the buffer is empty, the consumer cannot consume the elementin the program below, in indicates where the producer can join the data, out where the consumer can consume the databoth//in and out are initialized to 0, and we define in==out to indicate that the buffer is empty; (in+1)%n==out//Indicates that the buffer is full, but the way to fill it is to waste a space. The synchronized keyword is used in the previous example to ensure synchronization of buffer operations. the lock and condition classes are now required for synchronization control. Public classBuffer1 {PrivateFinal LockLock=NewReentrantlock ();PrivateFinal Condition con=Lock. Newcondition ();Private intNPrivate intBuffer1[];Private int inch;Private int out;Private intCnt/// Record the number of elements in the current bufferBuffer1 () {} Buffer1 (intN) { This. n=n; buffer1=New int[n];inch= out=cnt=0; }//Production method, add element x Public void Product(intx) {Lock.Lock();//Locking Try{if((inch+1)%n== out){//If the buffer is full, the current thread is blockedCon.await();//con.signalall ();}Else{buffer1[inch]=x;inch=(inch+1)%n; cnt++; System. out. println (Thread.CurrentThread (). GetName () +"adding elements to the buffer:"+X); System. out. println ("The number of elements in the current buffer is:"+CNT); Con.signalall ();//Wake up Other threads} }Catch(Interruptedexception ex) {Ex.printstacktrace (); }finally{/// Use the finally statement to ensure that the lock is released correctly Lock. Unlock (); } }//Consumption method, take one element in the buffer Public int Consumer(){intx=0;Lock.Lock();Try{if(inch== out){//If the buffer is empty, the current thread is blockedCon.await(); }Else{x=buffer1[ out]; System. out. println (Thread.CurrentThread (). GetName () +"consumption element:"+X); out=( out+1)%n; cnt--; System. out. println ("The current number of elements is:"+CNT); Con.signalall ();//Wake up Other threads} }Catch(Interruptedexception ex) {Ex.printstacktrace (); }finally{Lock. Unlock (); }returnX }}
PackageLKL1;ImportJava.util.Random;//Consumer thread Public class Consumer1 extends Thread{ PrivateRandom rand=NewRandom ();PrivateBuffer1 Buffer1;//The corresponding bufferConsumer1 (Buffer1 buffer1) { This. Buffer1=buffer1; } Public void Run(){ while(true) {Buffer1.consumer ();Try{//// Add a sleep statement to the consumer thread to better reflect the switching between threadsSleep -); }Catch(Exception x) {X.printstacktrace (); } } }}
PackageLKL1;ImportJava.util.Random;//Producer Threads Public class Product1 extends Thread{ PrivateRandom Rand =NewRandom ();PrivateBuffer1 Buffer1; Product1 (Buffer1 buffer1) { This. Buffer1=buffer1; } Public void Run(){ while(true){intX X=rand.nextint ( -); Buffer1.product (x); } }}
package lkl1; /// Buffer1 test //start a producer thread, two consumer threads public Span class= "Hljs-keyword" >class buffer1test {public static void main (string[] args) throws exception{Buffer1 buffer1 = new Buffer1 (1 0 ); new Product1 (Buffer1). Start (); new Consumer1 (Buffer1). Start (); new Consumer1 (Buffer1). Start (); }}
Three. Using blocking queues (blockingqueue) to control thread communication
JAVA5 provides a blockingqueue interface, which is also a sub-interface of the queue, but his primary function is to thread communication, not as a queue. The Blockingqueue feature is that when a producer thread attempts to add an element to a blockingqueue, the thread is blocked if the queue is full, and when the consumer thread tries to remove the element from the Blockingqueue, the thread is blocked if it is listed as empty.
The two threads of the program can control the communication of the thread well by alternately putting elements into the blocingqueue and removing the elements. Of course, not all Blockingqueue methods support blocking operations.
Blockingqueue provides the following two ways to support blocking:
Put (e): Attempts to put the E element into the blockingqueue, and if the element of the queue is full, the thread is blocked.
Take (): attempts to remove an element from the Blockingqueue's head, blocking the thread if the element of the queue is empty.
Other queue-corresponding methods are also supported, but in the above case the operation is not blocked, but instead returns false or throws an exception.
The common Blockingqueue implementation classes are as follows:
Arrayblockingqueue: Blockingqueue queue based on array implementation
Linkedblockingqueue: Blockingqueue queue based on linked list implementation
Priorityblockingqueue: the blocking queue corresponding to the priority queue
Synchronizedqueue: Synchronization queue, access to the queue must be alternately
Because the blocking queue natively supports the producer consumer model, it is easy to use blocking queues to implement producer consumer problems.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Thinking in Java---thread communication + three ways to implement producer consumer issues