Example12_8.java
Public class example12_8 { publicstaticvoid main (String args[]) { new tickethouse (); Thread Zhangfei,likui; New Thread (officer); Zhangfei.setname ("Zhang Fei") ; New Thread (officer); Likui.setname ("Li Kui"); Zhangfei.start (); Likui.start (); }}
Tickethouse.java
Public classTickethouseImplementsRunnable {intFiveamount=2,tenamount=0,twentyamount=0; Public voidrun () {if(Thread.CurrentThread (). GetName (). Equals ("Zhang Fei") {saleticket (20); } Else if(Thread.CurrentThread (). GetName (). Equals ("Li Kui") {saleticket (5); } } Private synchronized voidSaleticket (intMoney ) { if(money==5) {//if the thread that is using this method passes a parameter of 5, you do not have to waitFiveamount=fiveamount+1; System.out.println ("To" +thread.currentthread (). GetName () + "entry volume," +Thread.CurrentThread (). GetName ()+ "The money is just right"); } Else if(money==20) { while(fiveamount<3) { Try{System.out.println ("\ n" +thread.currentthread (). GetName () + "pull aside ..."); Wait (); //if the thread that uses the method passes the parameter is 20 must waitSystem.out.println ("\ n" +thread.currentthread (). GetName () + "continue to buy tickets"); } Catch(Interruptedexception e) {}} Fiveamount=fiveamount-3; Twentyamount=twentyamount+1; System.out.println ("To" +thread.currentthread (). GetName () + "entry volume," +Thread.CurrentThread (). GetName ()+ "Give 20, find redemption 15 yuan"); } notifyall (); } }
Bank.java
Public classBankImplementsRunnable {intmoney=200; Public voidSetmoney (intN) { money=N; } Public voidrun () {if(Thread.CurrentThread (). GetName (). Equals ("Accounting")) Saveortake (300); Else if(Thread.CurrentThread (). GetName (). Equals ("Cashier")) Saveortake (150);; } Public synchronized voidSaveortake (intAmount) {//access Method if(Thread.CurrentThread (). GetName (). Equals ("Accounting")) { for(inti=1;i<=3;i++) { money=MONEY+AMOUNT/3;//every deposit AMOUNT/3, a little restSystem.out.println (Thread.CurrentThread (). GetName () + "deposit" +amount/3+ ", the account has" +money+ "million, rest and then save"); Try{thread.sleep (1000);//The cashier still cannot use the Saveortake method } Catch(Interruptedexception e) {}}} Else if(Thread.CurrentThread (). GetName (). Equals ("Cashier")) { for(inti=1;i<=3;i++) {//The cashier uses the Access method to remove theMONEY=MONEY-AMOUNT/3;//every AMOUNT/3, take a break.System.out.println (Thread.CurrentThread (). GetName () + "Take Out" +amount/3+ "there is a" +money+ "on the account, rest for a while and then fetch"); Try{thread.sleep (1000);//then the accountant still can't use the Saveortake method } Catch(Interruptedexception e) {}}} }}
Java coordinated synchronization of threads