本篇实现的是龟兔赛跑的小案例
package lesson04;
/**
* 模拟龟兔赛跑
*/
public class TestThread4 implements Runnable{
String Winner;
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
Boolean flag =gameOver(i);
if (Thread.currentThread().getName().equals("兔子")&&i%10==0){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (flag.equals(true)){
break;
}
System.out.println(Thread.currentThread().getName()+"走了"+i+"步");
}
}
//判断是否完成比赛
public Boolean gameOver(int steps){
if (Winner!=null) {
return true;
}else {
if (steps >=100){
Winner=Thread.currentThread().getName();
System.out.println("winner==>"+Winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
TestThread4 thread4 = new TestThread4();
new Thread(thread4,"兔子").start();
new Thread(thread4,"乌龟").start();
}
}