JavaSE各阶段练习题----多线程
1、有一輛班車除司機外只能承載80個人,假設前中后三個車門都能上車,如果坐滿則不能再上車。
???請用線程模擬上車過程并且在控制臺打印出是從哪個車門上車以及剩下的座位數。
???比如:
?? (前門上車---還剩N個座...)
| package?com.henu; /* ?1、有一輛班車除司機外只能承載80個人,假設前中后三個車門都能上車,如果坐滿則不能再上車。 ???請用線程模擬上車過程并且在控制臺打印出是從哪個車門上車以及剩下的座位數。 ???比如: ?? (前門上車---還剩N個座...) ?*/ public?class?Test01 { public?static?void?main(String[] args) { ? BusDoor bDoor?= new?BusDoor(); ? Thread frond?= new?Thread(bDoor,"FROND->"); Thread centre?= new?Thread(bDoor,"CENTRE->"); Thread end?= new?Thread(bDoor,"END->"); ? frond.start(); centre.start(); end.start(); ? } } ? class?BusDoor implements?Runnable{ private?int?seat?= 80; @Override public?void?run() { ? while?(seat?<= 80) { synchronized?(this) { if?(seat?> 0) { try?{ Thread.sleep(100); } catch?(InterruptedException e) { e.printStackTrace(); } seat--; System.out.println(Thread.currentThread().getName() + "go on, there are "?+ seat?+ "seats"); }else?{ break; } } } } } ? |
?
| package?com.henu; ? ? /* 2、同時開啟3個線程,共同輸出100~200之間的所有數字,并且在輸出奇數的時候將線程名稱打印出來 ?*/ public?class?Test02 { public?static?void?main(String[] args) { PrintNumber pn?= new?PrintNumber(); ? Thread t1?= new?Thread(pn,"ThreadOne->"); Thread t2?= new?Thread(pn,"ThreadTwo->"); Thread t3?= new?Thread(pn,"ThreadThree->"); ? t1.start(); t2.start(); t3.start(); ? } } ? class?PrintNumber implements?Runnable{ ? private?int?start?= 100; ? @Override public?void?run() { ? while(start?< 200) { synchronized?(this) { if?(start?> 200) { break; }else?{ try?{ Thread.sleep(100); } catch?(InterruptedException e) { e.printStackTrace(); } if?(start?% 2 == 0) { System.out.println(start); }else?{ System.out.println(Thread.currentThread().getName() + start); } start++; } } } } } ? |
?
總結
以上是生活随笔為你收集整理的JavaSE各阶段练习题----多线程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaSE各阶段练习题----IO流
- 下一篇: JavaSE各阶段练习题----多线程-