資源描述:
《java多線程的實(shí)驗(yàn)--深圳大學(xué)郭治民》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫(kù)。
1、多線程的實(shí)驗(yàn)8.2.3吵醒休眠的線程1、代碼://ShopExample.javaclassShopimplementsRunnable{ThreadzhangWorker,wangWorker,boss;Shop(){boss=newThread(this);//創(chuàng)建boss,Shop對(duì)象為boss目標(biāo)對(duì)象zhangWorker=newThread(this);//創(chuàng)建zhangWorker,Shop對(duì)象為boss目標(biāo)對(duì)象wangWorker=newThread(this);//創(chuàng)建wangWorker,Shop對(duì)象為boss目標(biāo)對(duì)象zha
2、ngWorker.setName("張工");wangWorker.setName("王工");boss.setName("老板");}publicvoidrun(){inti=0;if(Thread.currentThread()==zhangWorker){while(true){try{i++;System.out.printf("%s已搬運(yùn)了%d箱蘋果",zhangWorker.getName(),i);if(i==3)return;Thread.sleep(10000);//zhangWorker休眠10秒(10000毫秒)
3、}catch(InterruptedExceptione){System.out.printf("%s讓%s繼續(xù)工作",boss.getName(),zhangWorker.getName());}}}elseif(Thread.currentThread()==wangWorker){while(true){try{i++;System.out.printf("%s已搬運(yùn)了%d箱香蕉",wangWorker.getName(),i);if(i==3)return;Thread.sleep(10000);//wangWorker休
4、眠10秒(10000毫秒)}catch(InterruptedExceptione){System.out.printf("%s讓%s繼續(xù)工作",boss.getName(),wangWorker.getName());}}}elseif(Thread.currentThread()==boss){while(true){zhangWorker.interrupt();//吵醒zhangWorkerwangWorker.interrupt();//吵醒wangWorkerif(!(wangWorker.isAlive()
5、
6、zhangWo
7、rker.isAlive())){System.out.printf("%n%s下班",boss.getName());return;}}}}}publicclassShopExample{publicstaticvoidmain(Stringargs[]){Shopshop=newShop();shop.zhangWorker.start();shop.wangWorker.start();shop.boss.start();}}2、結(jié)果截圖:8.2.4排隊(duì)買票1、代碼://SaleExample.javaclassTicketSeller
8、//負(fù)責(zé)賣票的類{intfiveNumber=1,tenNumber=0,twentyNumber=0;privateinttenNumber1;privateintfiveNumber1;publicsynchronizedvoidsellTicket(intreceiveMoney,intbuyNumber){if(receiveMoney==5){fiveNumber=fiveNumber+1;System.out.printf("%s給我5元錢,這是您的1張入場(chǎng)卷",Thread.currentThread().getName()
9、);}elseif(receiveMoney==10&&buyNumber==2){tenNumber=tenNumber+1;System.out.printf("%s給我10元錢,這是您的2張入場(chǎng)卷",Thread.currentThread().getName());}elseif(receiveMoney==10&&buyNumber==1){while(fiveNumber<1)//給出線程需等待的條件{try{System.out.printf("%30s靠邊等",Thread.currentThread().getNam
10、e());wait();//線程進(jìn)入等待狀態(tài)System.out.printf("%30s結(jié)束等待",Thread.currentThread().getN