Java實現(xiàn)多線程模擬龜兔賽跑
Java多線程模擬龜兔賽跑,供大家參考,具體內(nèi)容如下
筆者利用Java多線程技術(shù),將兔子和烏龜?shù)呐懿揭詢蓚€線程的方式模擬出來,以達(dá)到一個初步的效果。題目如下:路程總距離為35米兔子:每秒跑5米,每跑10米,休息2秒;烏龜:每秒跑3米,不休息。
所用工具
JDK1.8+IntelliJ IDEA 2020.1
代碼
Race.java:(線程類,通過new出來的對象的不同線程名,然后分別模擬兔子和烏龜?shù)呐懿剑?/p>
package task;import org.omg.Messaging.SYNC_WITH_TRANSPORT;public class Race extends Thread { private int mile=35;//剩下的路程 public int getMile() { return mile; } public void setMile(int mile) { this.mile = mile; } public void run(){ long time1=System.currentTimeMillis();//記錄開始跑的時間 if(getName().equals('兔子')){ while(mile>0) {if ((int)(System.currentTimeMillis()-time1) % 2000 == 0 && (int)(System.currentTimeMillis()-time1) != 0) {//每跑10米即每過2秒休息2秒 try { System.out.println('兔子正在休息2秒'); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }}if((int)(System.currentTimeMillis()-time1)%1000==0&& (int)(System.currentTimeMillis()-time1) != 0) { try { Thread.sleep(1000); mile -= 5; System.out.println('兔子跑了'+(35-mile)+'米');//35-mile即為跑過的距離 }catch(InterruptedException e){ e.printStackTrace(); }} } System.out.println('兔子到達(dá)終點'); }else if(getName().equals('烏龜')){ while(mile>0){if((int)(System.currentTimeMillis()-time1)%1000==0&& (int)(System.currentTimeMillis()-time1) != 0) { try { Thread.sleep(1000); mile -= 3; if(mile<0){ mile=0; } System.out.println('烏龜跑了'+(35-mile)+'米');//35-mile即為跑過的距離 }catch(InterruptedException e){ e.printStackTrace(); }} } System.out.println('烏龜?shù)竭_(dá)終點'); }else{ } }}
測試類demoo.java:(通過設(shè)置線程優(yōu)先級來實現(xiàn)烏龜先跑,否則線程執(zhí)行順序不可控?。。。?/p>
package task;public class demoo { public static void main(String[] args) { Thread rabbit=new Race(); rabbit.setName('兔子'); Thread turtle=new Race(); turtle.setName('烏龜'); turtle.setPriority(Thread.MAX_PRIORITY); rabbit.setPriority(Thread.MIN_PRIORITY); turtle.start(); rabbit.start(); }}
測試結(jié)果:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. js select支持手動輸入功能實現(xiàn)代碼2. 如何在PHP中讀寫文件3. java加載屬性配置properties文件的方法4. PHP正則表達(dá)式函數(shù)preg_replace用法實例分析5. 什么是Python變量作用域6. 《Java程序員修煉之道》作者Ben Evans:保守的設(shè)計思想是Java的最大優(yōu)勢7. CSS3中Transition屬性詳解以及示例分享8. php redis setnx分布式鎖簡單原理解析9. bootstrap select2 動態(tài)從后臺Ajax動態(tài)獲取數(shù)據(jù)的代碼10. vue使用moment如何將時間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時間格式
