Java多线程问题之龟兔赛跑
package Thread;
public class Demo04 implements Runnable{
private String winner;
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
if (Thread.currentThread().getName().equals("兔子")){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("兔子睡觉了");
}
}
boolean flag = gameover(i);
if (flag){
break;
}
System.out.println(Thread.currentThread().getName() + "跑了第" + i + "步");
}
}
public boolean gameover(int i){
if (winner != null){
return true;
}{
if (i>=100){
winner = Thread.currentThread().getName();
System.out.println(winner + "获得了胜利");
return true;
}
}
return false;
}
public static void main(String[] args) {
Demo04 demo04 = new Demo04();
new Thread(demo04,"乌龟").start();
new Thread(demo04,"兔子").start();
}
}
|