java多线程实现龟兔赛跑
程序员文章站
2022-05-02 10:10:00
...
package com.zhang.lesson.ThreadDenmon;
public class Race implements Runnable {
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (Thread.currentThread().getName().equals("兔子")){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
boolean flag=gameover(i);
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+ ">>>"+ "跑了" +i +"步");
}
}
private boolean gameover(int stpe) {
if (winner != null) {
return true;
}{
if (stpe==100){
winner=Thread.currentThread().getName();
System.out.println("winnner is "+ winner);
}
}
return false;
}
public static void main(String[] args) {
Race race =new Race();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}
运行结果:
上一篇: 别让过分追求完美毁了自己
下一篇: java多线程经典案例:龟兔赛跑