Java Condition collaborative thread interface class, javacondition
In the Java Condition interface, several methods exist in the same way as the wait (), waitall (), and wait (time ^) methods in Synchronized. the specified thread can be specified to release and wait for resources in the return result of newCondition.See [wake up a single thread] instance:
Package TestThread. testCondition; import java. util. concurrent. locks. reentrantLock; import java. util. concurrent. locks. *; public class TestCondition {public static void main (String [] args) {ReentrantLock lock = new ReentrantLock (); Condition condition = lock. newCondition (); Test1 th1 = new Test1 (lock, condition, "thread 1"); Test1 th1 = new Test1 (lock, condition, "thread 2 "); test1 th3 = new Test1 (lock, condition, "Line Process 3 "); Test2 t2 = new Test2 (condition, lock," I am a wake-up Thread "); th1.start (); th2.start (); th3.start (); try {Thread. sleep (1000); t2.start ();} catch (InterruptedException e) {e. printStackTrace () ;}} class Test1 extends Thread {private ReentrantLock lock; private Condition condition1; public Test1 (ReentrantLock lock, Condition condition1, String name) {super (name); this. lock = lock; this. condition1 = condition1;} @ Overri Depublic void run () {for (int I = 0; I <10; I ++) {try {lock. lock (); // lock if (I = 5) {try {condition1.await (); System. out. println (Thread. currentThread (). getName () + "the value obtained by the current thread is: ++" + I);} catch (InterruptedException e) {System. out. println (Thread. currentThread (). getName () + ": The thread is interrupted! ") ;}} Else {System. out. println (Thread. currentThread (). getName () + ": the value obtained by the current thread is ==="" + I) ;}} catch (Exception e) {System. out. println ("system exception! ");} Finally {lock. unlock (); // unlock }}} class Test2 extends Thread {private Condition condition; public ReentrantLock lock; /*** @ param condition collaboration object * @ param lock object * @ param name thread name */public Test2 (Condition condition, ReentrantLock lock, String name) {super (name); this. condition = condition; this. lock = lock ;}@ Overridepublic void run () {try {lock. lock (); // lock condition. signal (); // wake up to start a single thread System. out. pr Intln (Thread. currentThread (). getName () + ": A Thread has been awakened! ");} Catch (Exception e) {System. out. println (Thread. currentThread (). getName () +": the Thread has crashed! ");} Finally {lock. unlock (); // unlock }}}
Running result: 2017-03-2501: 16: 17