Java執行緒實現簡單的龜兔賽跑
阿新 • • 發佈:2021-01-17
龜兔賽跑
//龜兔賽跑
public class Match implements Runnable {
private String name;
//實現run方法
@Override
public void run() {
//你可以讓兔子睡覺
//由於兔子跑的太快,所以模擬兔子休息
// if (Thread.currentThread().getName().equals("兔子")){
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// e.printStackTrace();
//}
// }
//迴圈,總路程100米
for (int i = 1; i <=50 ; i++) {
//判斷結束,呼叫getmatch()方法,為true則比賽結束
if (getmatch(i)==true){
break;
}
System. out.println(Thread.currentThread().getName()+"跑了"+i+"米");
}
}
//以下方法判斷誰獲勝,sleep 表示路程
private boolean getmatch(int sleep){
//判斷是否有勝利者
if(name!=null){ //存在勝利者,就會結束程式
return true;
}else
if(sleep>=50){ //誰先跑夠50米,就結束程式,終止比賽
name= Thread.currentThread().getName();
System.out.println("勝利者:"+name);
return true;
}else {
return false; //都不成立返回false
}
}
public static void main(String[] args) {
Match match=new Match();
new Thread(match,"兔子").start();
new Thread(match,"烏龜").start();
}
}
結果: