Key Code 1
Private Lock New Reentrantlock (); Private Lock . Newcondition (); Private lock. newcondition ();
Key Code 2
R.getlock (). Lock ();
Try {R.getcondition_pro (). await ();} Catch (Exception e) {}r.getcondition_con (). Signalall (); R.getlock (). Unlock ();
Full code:
Package Songyan;import java.util.concurrent.locks.*; classres{PrivateLockLock=NewReentrantlock (); PublicLock Getlock () {return Lock; } Public voidSetlock (LockLock) { This.Lock=Lock; } PrivateCondition Condition_pro =Lock. Newcondition (); PublicCondition Getcondition_pro () {returnCondition_pro; } Public voidSetcondition_pro (Condition condition_pro) { This. Condition_pro =Condition_pro; } PublicCondition Getcondition_con () {returnCondition_con; } Public voidSetcondition_con (Condition condition_con) { This. Condition_con =Condition_con; } PrivateCondition Condition_con =Lock. Newcondition (); PrivateString name; Private intID; PrivateBoolean flag; PublicBoolean Getflag () {returnFlag; } Public voidSetflag (Boolean flag) { This. flag=Flag; } PublicString GetName () {returnname; } Public intgetId () {returnID; } Public voidsetName (String name) { This. name=name; } Public voidSetId (intID) { This. id=ID; } } classPro implements runnable{PrivateRes R; Public voidrun () {intx=0; while(true) {R.getlock ().Lock(); while(R.getflag ())Try{R.getcondition_pro ().await();}Catch(Exception e) {}if(x==0) {R.setname ("Zhang San"); R.setid (R.getid ()+1); System. out. println (R.getname () +"* * Production * * * *"+R.getid ()); } Else{r.setname ("Zhangsan"); R.setid (R.getid ()+1); System. out. println (R.getname () +"* * Production * * * *"+R.getid ()); } x= (x+1)%2; R.setflag (true); R.getcondition_con (). Signalall (); R.getlock (). Unlock (); }} Pro (Res r) { This. r=R; } } classCons implements runnable{PrivateRes R; Public voidrun () { while(true) {R.getlock ().Lock(); while(!R.getflag ())Try{R.getcondition_con ().await();}Catch(Exception e) {} System. out. println (R.getname () +"* * * Consumer * * *"+R.getid ()); R.setflag (false); R.getcondition_pro (). Signalall (); R.getlock (). Unlock (); }} Cons (Res r) { This. r=R; } } Public classtest{ Public Static voidMain (string[] args) {Res R=NewRes (); Pro P=NewPro (R); Cons C=NewCons (R); Thread T1=NewThread (P); Thread T2=NewThread (c); Thread T3=NewThread (P); Thread T4=NewThread (c); T1.start (); T2.start (); T4.start (); T3.start (); } }
13, multithreading-producer consumer issues 2