The lock implementation provides a wider range of locking operations than is possible with synchronized methods and statements.
This implementation allows for a more flexible structure that can have very different properties and can support multiple related Condition objects.
Use producers and consumers as an example!!!
Import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.lock;import java.util.concurrent.locks.reentrantlock;/** * Use lock and condition instead of * synchronized and wait, notify Notifyall (); */class resource2{private String product;private int count = 1;private Boolean flag= false;private lock lock = new Reentra NTLock (); Condition Condition_pro = Lock.newcondition (); Lock the creators of the condition to the elephant!! Condition Condition_con = Lock.newcondition (); Lock the creators of the consumer condition to the elephant!! public void produce (String product) throws Interruptedexception{lock.lock (), try {while (flag) {condition_pro.await ();} This.product = product+ "----" + count++; System.out.println (Thread.CurrentThread (). GetName () + "———— produced ————" +this.product); flag= true;condition_con.signal (); Awaken the consumer to the elephant!!! }finally{lock.unlock ();}} public void consume () throws Interruptedexception{lock.lock (), try {while (!flag) {condition_con.await ();} System.out.println (Thread.CurrentThread (). GetName () + "———— consumer ————" +this.product); flag= False;condition_ Pro.signal (); AwakenProducer to the Elephant!!! }finally{lock.unlock ();}}} Class Producer2 implements Runnable{private Resource2 res;public Producer2 (Resource2 res) {this.res= res;} @Overridepublic void Run () {while (true) {try {res.produce ("Iphone 7");} catch (Interruptedexception e) {//TODO Auto-gener Ated catch Blocke.printstacktrace ();}}} Class Consumer2 implements Runnable{private Resource2 res;public Consumer2 (Resource2 res) {this.res= res;} @Overridepublic void Run () {while (true) {try {res.consume ()} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} public class ProducerComsumer2 {public static void main (string[] args) {Resource2 res = new Resource2 (); Producer2 Pro = new Producer2 (res); Consumer2 con = new Consumer2 (res); thread T1 = new Thread (Pro, "producer 1"); Thread t2 = new Thread (Pro, "producer 2"); thread t3 = new Thread (Con, "Consumer 1"); thread T4 = new thread (Con, "Consumer 2"); T1.start (); T2.start (); T3.start (); T4.start ();//new Thread (New Producer (res)). Start ();//new Thread (New Consumer (res)). Start ();}}
Java thread Communication-use lock and condition instead of synchronized and wait, notify Notifyall ()