Background:
The last article based on the object of Wait, notify realized the producer, consumer model. This article continues to comb the condition. Condition Introduction and demo
Condition is present in Java 1.5, which replaces the traditional wait (), notify () of the object to implement the collaboration between threads, compared to the Wait (), notify () using object, await (), Signal () This approach enables more secure and efficient threading collaboration. Therefore, it is generally recommended that condition be used, and blocking queues actually use condition to simulate the collaboration between threads. Condition is an interface, the basic method is the await () and signal () method, condition relies on the lock interface, generating a condition Basic code is lock.newcondition () Calls to condition's await () and signal () methods must be within lock protection, meaning that you must be able to use between Lock.lock () and Lock.unlock
The await () in the Conditon corresponds to the Wait () of object;
The signal () in the condition corresponds to the Notify () of the object;
The Signalall () in the condition corresponds to the Notifyall () of the object.
Here is the demo:
Package thread;
Import java.util.concurrent.locks.Condition;
Import Java.util.concurrent.locks.Lock;
Import Java.util.concurrent.locks.ReentrantLock; /** * * * * * * * @author Zhangliang * * * * * * * * April 8, 2016 PM 5:48:54/public class ConTest {final lock lock = new Reentrantlock
();
Final Condition Condition = Lock.newcondition ();
public static void Main (string[] args) {//TODO auto-generated method stub ConTest test = new ConTest ();
Producer Producer = Test.new Producer ();
Consumer Consumer = Test.new Consumer ();
Consumer.start ();
Producer.start ();
Class Consumer extends thread{@Override public void Run () {consume ();
private void consume () {try {
Lock.lock ();
System.out.println ("I'm waiting for a new signal" +this.currentthread (). GetName ());
Condition.await ();
catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ()
;
finally{System.out.println ("Get a Signal" +this.currentthread (). GetName ());
Lock.unlock (); {}} class Producer extends thread{@Override public void ru
N () {produce ();
private void produce () {try {lock.lock ();
System.out.println ("I Got the Lock" +this.currentthread (). GetName ());
Condition.signalall ();
SYSTEM.OUT.PRINTLN ("I sent a signal:" +this.currentthread (). GetName ());
} finally{Lock.unlock ();
}
}
}
}Run Result:
The way condition is executed is when the await method is invoked in the thread consumer, the threads consumer will release the lock, and will sleep, wait for wake, thread producer get to the lock, start doing things, Calls the condition Signalall method, wakes the thread consumer, and the thread consumer resumes execution.
The above description Condition is a tool class that coordinates communication between multithreading, making some, or some threads, wait for a certain condition (Condition), which is awakened only if the condition has (signal or Signalall method is called). And then scramble for the lock again. condition realize producer and consumer mode:
Package thread;
Import Java.util.PriorityQueue;
Import java.util.concurrent.locks.Condition;
Import Java.util.concurrent.locks.Lock;
Import Java.util.concurrent.locks.ReentrantLock;
public class ConTest2 {private int queuesize = 10;
Private priorityqueue<integer> queue = new priorityqueue<integer> (queuesize);
Private lock lock = new Reentrantlock ();
Private Condition Notfull = Lock.newcondition ();
Private Condition Notempty = Lock.newcondition ();
public static void Main (string[] args) throws interruptedexception {ConTest2 test = new ConTest2 ();
Producer Producer = Test.new Producer ();
Consumer Consumer = Test.new Consumer ();
Producer.start ();
Consumer.start ();
Thread.Sleep (0);
Producer.interrupt ();
Consumer.interrupt (); Class Consumer extends thread{@Override public void Run () {cons
Ume (); } volatile Boolean flag=true;
private void Consume () {while (flag) {Lock.lock (); try {while (Queue.isempty ()) {try {System.out.
println ("Queue empty, waiting for data");
Notempty.await ();
catch (Interruptedexception e) {flag =false; } queue.poll ();
Notfull.signal () each time the first element of the team is removed;
System.out.println ("Take an element from the queue, the queue remaining" +queue.size () + "element");
} finally{Lock.unlock (); Class Producer extends thread{@Override Publ
IC void Run () {produce ();
} volatile Boolean flag=true; private void produce () {while (flag) {Lock.lock (); try {while (queue.size () = = Queuesize) {try {S
Ystem.out.println ("Queue full, waiting for free space");
Notfull.await ();
catch (Interruptedexception e) {flag =false; } queue.offer (1);
Inserts one element at a time notempty.signal ();
SYSTEM.OUT.PRINTLN ("Inserts an element into the queue, the queue remaining space:" + (Queuesize-queue.size ()));
} finally{Lock.unlock ();
}
}
}
}
}The results of the operation are as follows:
Condition Implementation Analysis:
The condition interface contains a variety of await methods and two notification methods Conditionobject implements the condition interface, which is the inner class of the Abstractqueuedsynchronizer Reentrantlock Newcondition method returns the condition object associated with a lock instance
Public abstract class Abstractqueuedlongsynchronizer
extends Abstractownablesynchronizer
implements java.io.Serializable {
<span style= "FONT-SIZE:18PX;" > combining the above class diagram, we see that the condition implementation is dependent on AQS, and Aqs is an abstract class. The basic framework of the Synchronizer is defined and the basic structure function is realized. Only the maintenance of state conditions by the specific Synchronizer according to the specific scene to customize, such as Common Reentrantlock, Retrantreadwritelock and Countdownlatch, Aqs content too much, as far as possible only concise comb condition related processes , not too deep understanding of the underlying source code. </span>
The following combination of the above demo to analyze the process. Reentrantlock.newcondition () returns an implementation of the condition, which is implemented in Abstractqueuedsynchronizer (AQS), called Newcondition ()
Public Condition newcondition () {return
sync.newcondition ();
}
Let's take a look at this await method, it's a Aqs method,
| Public final void await () throws Interruptedexception { |
| 02 |
if (thread.interrupted ()) |
| 03 |
throw new Interruptedexception (); |
| 04 |
Node node = Addconditionwaiter (); After wrapping the current thread, |
| 05 |
Added to a list of condition's own maintenance. |
| 06 |
int savedstate = fullyrelease (node);/release the current thread-occupied lock, see from Demo |
| 07 |
The current thread is a possession lock before the await is invoked |