1.Condition Introduction
In the previous article mentioned the object of the wait and notify method, condition class is actually this method of an alternative product.
The condition object is used in conjunction with lock and is created by lock. And the caller of the condition.await must get lock, which automatically releases the lock at await, and then acquires the lock when it is signal by another thread, a similar use for the sychronized mentioned in the previous blog. 2. Producer consumer procedures based on condition
(seemingly arrayblockingqueue) here use Notfull and notempty to indicate that there is a condition for the elements in the linked list, the specific code is as follows:
package concurrency;
/** * Created by Wangxiaoyi on 15/11/18.
* * Import java.util.LinkedList;
Import java.util.List;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import java.util.concurrent.locks.Condition;
Import Java.util.concurrent.locks.Lock;
Import Java.util.concurrent.locks.ReentrantLock;
public class ProducerAndConsumer2 {private list<integer> data = new linkedlist<> ();
private static final int max_data_len = 10;
Private lock lock = new Reentrantlock ();
Private Condition Notempty = Lock.newcondition ()//Non-empty condition private Condition notfull = Lock.newcondition ();//Not full condition
Class Producer implements Runnable {private int pid = 0;
public Producer (int pid) {this.pid = pid; public void Run () {try {) ' while '!
Thread.CurrentThread (). isinterrupted ()) {lock.lock (); while (Data.size () >= MAX_data_len) {System.out.println ("Producer" + pid + "Waiting!")
Size: "+ data.size ()); Notfull.await ();
Wait for notfull.signal to wake Up} try{Data.add (PID); Notempty.signal (); Wake notempty.await () thread System.out.println ("Producer" + pid + "Add" + pid + "size:" + data.siz
E ());
}finally {lock.unlock ();
} thread.sleep (500);
} catch (Interruptedexception IE) {ie.printstacktrace ();
}} class Consumer implements runnable{private int cid = 0;
Public Consumer (int cid) {this.cid = CID; public void Run () {try {) ' while '!
Thread.CurrentThread (). isinterrupted ()) {lock.lock (); while (Data.isempty ()) {System.out.println ("Consumer + cid +" waiting, data size:
"+ data.size ());
Notempty.await ();
} try{int pid = data.remove (0);
Notfull.signal ();
System.out.println ("Consumer" + CID + "consuming data" + PID + "Data size:" + data.size ());
}finally {lock.unlock ();
} thread.sleep (500);
}}catch (Interruptedexception IE) {ie.printstacktrace ();
}} public void Start () {Executorservice executor = Executors.newcachedthreadpool ();
for (int i = 0; i < 5; + + i) {executor.submit (new Producer (i));
Executor.submit (New Consumer (i));
try {thread.sleep (10*1000); catch (Interruptedexception e) {e.printstacktrace ();
} executor.shutdownnow ();
public static void Main (String []args) {new ProducerAndConsumer2 (). Start ();
}
}