public class RaceRG implements Runnable{
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 1000; i++) {
//兔子跑到一半休息一会
if (Thread.currentThread().getName().equals("兔子") && i==500){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
boolean flag = gameOver(i);
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"-->跑了"+i);
}
}
//判断谁先跑满1000米
public boolean gameOver(int step){
if (winner != null){
return true;
}else{
if (step >= 1000){
winner = Thread.currentThread().getName();
System.out.println("winner is "+winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
/*同一个资源被多个线程使用*/
RaceRG rg = new RaceRG();
new Thread(rg,"兔子").start();
new Thread(rg,"乌龟").start();
}
}
Thread多线程样例--龟兔赛跑
最新推荐文章于 2024-05-23 21:16:33 发布