Before using lock, we should use the most synchronous method is the Synchronized keyword to achieve synchronization. The Wait (), notify () series method with object can implement the await/Notify mode. The condition interface also provides an object-like monitor method that can be used with lock mates to implement the wait/Notify mode, but the two are still different in terms of usage and feature characteristics. Some comparisons between the object and the condition interface. From the art of Java concurrency programming
First, condition interface Introduction and Example
First we need to understand that the condition object is dependent on the lock object, meaning that the condition object needs to be created by the lock object (calling the Newcondition () method of the lock object). The way the consition is used is very simple. However, it is important to take care to get the lock before calling the method.
1 PackageCom.ydl.test.juc;2 3 ImportJava.util.concurrent.ExecutorService;4 ImportJava.util.concurrent.Executors;5 ImportJava.util.concurrent.locks.Condition;6 ImportJava.util.concurrent.locks.Lock;7 ImportJava.util.concurrent.locks.ReentrantLock;8 9 Public classConditionusecase {Ten One PublicLock lock =NewReentrantlock (); A PublicCondition Condition = Lock.newcondition (); - - Public Static voidMain (string[] args) { theConditionusecase UseCase =NewConditionusecase (); -Executorservice Executorservice = Executors.newfixedthreadpool (2); -Executorservice.execute (NewRunnable () { -@Override + Public voidRun () { -Usecase.conditionwait (); +} A}); atExecutorservice.execute (NewRunnable () { -@Override - Public voidRun () { -Usecase.conditionsignal (); -} -}); in} - to Public voidConditionwait () { +Lock.lock (); - Try{ theSystem.out.println (Thread.CurrentThread (). GetName () + "got the lock."); *System.out.println (Thread.CurrentThread (). GetName () + "wait for the signal"); $Condition.await ();Panax NotoginsengSystem.out.println (Thread.CurrentThread (). GetName () + "get the signal ."); -}Catch(Exception e) { the +}finally{ ALock.unlock (); the} +} - Public voidConditionsignal () { $Lock.lock (); $ Try{ -Thread.Sleep (5000); -System.out.println (Thread.CurrentThread (). GetName () + "got the lock."); theCondition.signal (); -System.out.println (Thread.CurrentThread (). GetName () + "Send a signal");Wuyi}Catch(Exception e) { the -}finally{ WuLock.unlock (); -} About} $ -} - -
1 pool-1-thread-1 got the lock, 2 pool-1-thread-1 wait for the signal, 3 pool-1-thread-2 got the lock. 4 pool-1-thread-2 signal 5 pool-1-thread-1 get the signal.
As the example shows, the condition object is generally used as a member variable. When the await () method is called, the current thread releases the lock and waits, while the other thread calls the signal () method of the Condition object, notifies the current thread that the current line friend is returned from the await () method, and acquires the lock before returning.
Two, condition interface common method
Condition can be commonly understood as conditional queuing. When a thread calls the await method, it is not awakened until a condition that the thread waits for is true. This approach provides a simpler wait/notification pattern for threads. Condition must be used with locks, because access to shared state variables occurs in a multithreaded environment. An instance of condition must be bound to a lock, so condition is generally used as the internal implementation of lock.
-
await () : Causes the current thread to wait until it receives a signal or is interrupted.
-
await (long time, timeunit unit) : Causes the current thread to wait until it receives a signal, is interrupted, or arrives at a specified wait time.
-
Awaitnanos (Long nanostimeout) : Causes the current thread to wait until it receives a signal, is interrupted, or arrives at a specified wait time. The return value indicates the time remaining, if awakened before Nanostimesout, then the return value = nanostimeout-time spent, if the return value <= 0, you can assume that it has timed out.
-
awaituninterruptibly () : Causes the current thread to be in a wait state until the signal is received. "Note: This method is insensitive to interrupts."
-
Awaituntil (Date deadline) : Causes the current thread to wait until it receives a signal, is interrupted, or arrives at a specified deadline. Returns true if it is not notified at the specified time, or returns False if the specified time is indicated.
-
signal () : Wakes up a waiting thread. The thread must obtain a condition-related lock before returning from the wait method.
-
signal () all: Wakes all waiting threads. The thread that can be returned from the wait method must obtain the lock associated with the condition.
Three, condition interface principle simple analysis
Condition is the inner class of Aqs. Each condition object contains a queue (waiting queue). The wait queue is a FIFO queue, and each node in the queue contains a thread reference, which is the thread that waits on the condition object, and if a thread calls the Condition.await () method, the thread releases the lock, Constructs a node to join the wait queue and enters the wait state. The basic structure of the wait queue is shown below.
The wait is divided into the first node and the tail node. When a thread calls the Condition.await () method, it constructs the node in the current thread and joins the node from the trailer to the waiting queue. The new node is to point the tail node to the new node. A node reference update would have been an operation after acquiring a lock, so there is no need for CAS assurance. It is also a thread-safe operation.
3.2. Wait
After the thread calls the await method. The thread is added to the wait queue as a node in the queue. It also releases the ownership of the lock. When returning from the await method. The lock associated with the condition must be acquired. When a node in the wait queue wakes up, the thread that wakes the node starts trying to get the synchronization state. If the Condition.signal () method is not invoked by another thread, but instead is interrupted by a waiting thread, the interruptedexception exception message is thrown.
3.3. Notice
Calling condition's signal () method will wake up the node waiting for the longest time in the waiting queue (the first node in the condition queue), and move the node to the synchronization queue before waking the node. The current thread joins the wait queue:
Before calling the signal () method, you must first determine whether the lock is acquired. It then gets the first node of the wait queue, moves it to the synchronization queue, and wakes up the thread in the node with Locksupport. The node moves from the waiting queue to the synchronization queue as shown in:
The awakened thread exits from the while loop in the await method. Then join the race to the sync state. A thread that successfully acquires the competition will return to the state before the await method.
Iv. Summary
After the await method is called, the current thread is joined to the condition wait queue. The current thread releases the lock. Otherwise, the other thread cannot get the lock and a deadlock occurs. The spin (while) hangs, continuously detects whether the node is in the synchronization queue, and if so, tries to acquire the lock, otherwise hangs. When the thread is awakened by the signal method, the awakened thread exits from the while loop in the await () method, and then calls the Acquirequeued () method to compete for the synchronization state.
V. Using condition to achieve the producer consumer model
1 2 ImportJava.util.LinkedList;3 ImportJava.util.concurrent.locks.Condition;4 ImportJava.util.concurrent.locks.Lock;5 ImportJava.util.concurrent.locks.ReentrantLock;6 7 Public classBoundedqueue {8 9 PrivateLinkedlist<object> buffer;//producer ContainersTen Private intMaxSize;//What is the maximum container size ? One PrivateLock lock; A PrivateCondition fullcondition; - PrivateCondition notfullcondition; -Boundedqueue (intMaxSize) { the This. maxSize = maxSize; -Buffer =NewLinkedlist<object> (); -Lock =NewReentrantlock (); -Fullcondition = Lock.newcondition (); +Notfullcondition = Lock.newcondition (); -} + A /** * producer * @param obj * @throws interruptedexception */ - Public voidPut (Object obj)throwsinterruptedexception { -Lock.lock ();//Get lock in Try{ - while(MaxSize = = Buffer.size ()) { toNotfullcondition.await ();//full, the added thread goes into a wait state +} -Buffer.add (obj); theFullcondition.signal ();//Notification *}finally{ $Lock.unlock ();Panax Notoginseng} -} the + /** * consumer * @return * @throws interruptedexception */ $ PublicObject get ()throwsinterruptedexception { $Object obj; -Lock.lock (); - Try{ the while(buffer.size () = = 0) {//No data in queue the thread goes into a wait state -Fullcondition.await ();Wuyi} theobj = Buffer.poll (); -Notfullcondition.signal ();//Notification Wu}finally{ -Lock.unlock (); About} $ returnObj -} - -} A
Reference:
The art of Java concurrent programming
Java Concurrency Programming Network
Java Concurrency condition