JDK1.5 the lock interface instead of synchronized to the display lock mechanism,
Wait, notify, Notifyall in object are replaced with await, signal, signalall in condition objects can be obtained by lock
This example implements the action that the local thread only wakes the other thread
Importjava.util.concurrent.locks.*;/*a multi-threaded upgrade solution is available in JDK1.5. Replace the sync synchronized with the show lock operation. Replaces the condition object with the Wait,notify Notifyall in object. The object can be obtained by lock lock. In this example, the party only wakes the other action. Lock: Replaces synchronized lock unlock newcondition () Condition: Replaces object wait notify Notifyall await (); Signal (); Signalall ();*/classlockdemo{ Public Static voidMain (string[] args) {Resource R=NewResource (); Producer Pro=Newproducer (R); Consumer Con=Newconsumer (R); Thread T1=NewThread (PRO); Thread T2=NewThread (PRO); Thread T3=NewThread (con); Thread T4=NewThread (con); T1.start (); T2.start (); T3.start (); T4.start ();//thread T11 = new Thread (PRO);//thread t22 = new Thread (PRO);//thread t33 = new Thread (con);//thread T44 = new Thread (con);//T11.start ();//T22.start ();//T33.start ();//T44.start (); }}//Resource Classclassresource{PrivateString name; Private intCount = 1; Private BooleanFlag =false; //set Lock Object PrivateLock lock =NewReentrantlock (); //set the condition object for a controlled sleep wake operation on a threadCondition Condition_pro = Lock.newcondition ();//for producer OperationsCondition Condition_con = Lock.newcondition ();//for consumer operations//Set Resource Name Public voidset (String name) {Lock.lock (); Try { while(flag) {condition_pro.await (); } This. Name = name+ "---" +count++; System.out.println (Thread.CurrentThread (). GetName ()+"..."+name); Flag=true; Condition_con.signal (); } Catch(Exception e) {}finally{lock.unlock ();//The action of releasing the lock is placed in the finally so that it is bound to be executed. } } //Get Resources (consumer resources) Public voidget () {Try{lock.lock (); while(!flag) {condition_con.await (); } System.out.println (Thread.CurrentThread (). GetName ()+".........."+name); Flag=false; Condition_pro.signal (); } Catch(Exception e) {}finally{lock.unlock (); } }}//Producer ClassclassProducerImplementsrunnable{PrivateResource R; Producer (Resource R) { This. R =R; } Public voidrun () { while(true) {R.set ("+ Products +"); } }}//Consumer classclassConsumerImplementsrunnable{PrivateResource R; Consumer (Resource R) { This. R =R; } Public voidrun () { while(true) {r.get (); } }}
View Code
Jdk1.5--synchronized upgrade (displayed lock action)