package pojo; //包名
public class Race implements java.lang.Runnable {
private static String win;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (Thread.currentThread().getName().equals("兔子")&&i%10==0){//给乌龟赢
try {
Thread.sleep(1);//线程睡眠1毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}}
boolean flag=gameover(i);//判断赢没
if (flag) {
break;
}
System.out.println(Thread.currentThread().getName()+"-->跑了"+i+"步");
}
}
public boolean gameover(int step){
if(win!=null){
return true;
}{
if (step==100){//说明赢了
win=Thread.currentThread().getName();//获取名字
System.out.println("winner is "+win);
return true;
}
}
return false;
}
public static void main(String[] args) {
Race obj=new Race();
new Thread(obj,"兔子").start();
new Thread(obj,"乌龟").start();
}
}
java-多线程之龟兔赛跑
最新推荐文章于 2024-05-23 18:11:39 发布