Importjava.util.concurrent.locks.*; classDo9 { Public Static voidMain (string[] args) {Resource R=NewResource (); Shengchan SC=NewShengchan (R); Xiaoshou XS=NewXiaoshou (R); Thread Th1=NewThread (SC); Thread Th2=NewThread (SC); Thread Th3=NewThread (XS); Thread Th4=NewThread (XS); Th1.start (); Th2.start (); Th3.start (); Th4.start (); }}classresource{PrivateString name; Private intCount=1; Private Booleanflag=false; //Create a lock pair likeLock lock=NewReentrantlock (); //Gets the monitor object for the lock by the existing locksCondition shengchan_con=lock.newcondition ();//Create a Producer objectCondition xiaofei_con=lock.newcondition ();//Create consumer Objects Public voidset (String name) {Lock.lock (); Try { while(flag)Try{shengchan_con.await ();}Catch(Interruptedexception e) {} This. name=name+count; Count++; System.out.println (Thread.CurrentThread (). GetName ()+".. Producer: " + This. Name); Flag=true; Xiaofei_con.signal (); } finally{lock.unlock (); } } Public synchronized voidout () {lock.lock (); Try { while(!flag)Try{xiaofei_con.await ();}Catch(Interruptedexception e) {} System.out.println (Thread.CurrentThread (). GetName ()+".. Consumer ... "+ This. Name); Flag=false; Shengchan_con.signal (); } finally{lock.unlock (); } }}classShengchanImplementsrunnable{PrivateResource R; Shengchan (Resource r) { This. r=R; } Public voidrun () { while(true) { Try{Thread.Sleep (150);}Catch(Interruptedexception e) {} r.set (Duck); } }}classXiaoshouImplementsrunnable{PrivateResource R; Xiaoshou (Resource r) { This. r=R; } Public voidrun () { while(true) { Try{Thread.Sleep (150);}Catch(Interruptedexception e) {} r.out (); } }}
Wake up specified line layer object in Java new version