资源描述:
《java多线程的实验--深圳大学郭治民》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、多线程的实验8.2.3吵醒休眠的线程1、代码://ShopExample.javaclassShopimplementsRunnable{ThreadzhangWorker,wangWorker,boss;Shop(){boss=newThread(this);//创建boss,Shop对象为boss目标对象zhangWorker=newThread(this);//创建zhangWorker,Shop对象为boss目标对象wangWorker=newThread(this);//创建wangWorker,Shop对象为boss目标对象zha
2、ngWorker.setName("张工");wangWorker.setName("王工");boss.setName("老板");}publicvoidrun(){inti=0;if(Thread.currentThread()==zhangWorker){while(true){try{i++;System.out.printf("%s已搬运了%d箱苹果",zhangWorker.getName(),i);if(i==3)return;Thread.sleep(10000);//zhangWorker休眠10秒(10000毫秒)
3、}catch(InterruptedExceptione){System.out.printf("%s让%s继续工作",boss.getName(),zhangWorker.getName());}}}elseif(Thread.currentThread()==wangWorker){while(true){try{i++;System.out.printf("%s已搬运了%d箱香蕉",wangWorker.getName(),i);if(i==3)return;Thread.sleep(10000);//wangWorker休
4、眠10秒(10000毫秒)}catch(InterruptedExceptione){System.out.printf("%s让%s继续工作",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、结果截图:8.2.4排队买票1、代码://SaleExample.javaclassTicketSeller
8、//负责卖票的类{intfiveNumber=1,tenNumber=0,twentyNumber=0;privateinttenNumber1;privateintfiveNumber1;publicsynchronizedvoidsellTicket(intreceiveMoney,intbuyNumber){if(receiveMoney==5){fiveNumber=fiveNumber+1;System.out.printf("%s给我5元钱,这是您的1张入场卷",Thread.currentThread().getName()
9、);}elseif(receiveMoney==10&&buyNumber==2){tenNumber=tenNumber+1;System.out.printf("%s给我10元钱,这是您的2张入场卷",Thread.currentThread().getName());}elseif(receiveMoney==10&&buyNumber==1){while(fiveNumber<1)//给出线程需等待的条件{try{System.out.printf("%30s靠边等",Thread.currentThread().getNam
10、e());wait();//线程进入等待状态System.out.printf("%30s结束等待",Thread.currentThread().getN