Java實現(xiàn)多線程模擬龜兔賽跑
Java多線程模擬龜兔賽跑,供大家參考,具體內(nèi)容如下
筆者利用Java多線程技術(shù),將兔子和烏龜?shù)呐懿揭詢蓚€線程的方式模擬出來,以達到一個初步的效果。
題目如下:路程總距離為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("兔子到達終點");
}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ù)竭_終點");
}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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳談Java中net.sf.json包關(guān)于JSON與對象互轉(zhuǎn)的坑
下面小編就為大家分享一篇Java中net.sf.json包關(guān)于JSON與對象互轉(zhuǎn)的坑,具有很好的參考價值,希望對大家有所幫助2017-12-12
創(chuàng)建網(wǎng)關(guān)項目(Spring Cloud Gateway)過程詳解
這篇文章主要介紹了創(chuàng)建網(wǎng)關(guān)項目(Spring Cloud Gateway)過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-09-09
SpringBoot?項目打成?jar后加載外部配置文件的操作方法
這篇文章主要介紹了SpringBoot?項目打成?jar后加載外部配置文件的操作方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03

