wkx_java
Kennan Wang
2017-10-16 09:22

Java多线程龟兔赛跑问题

  • java
  • 线程

public class RabbitAndTurtle extends Thread{
public int num;
public static boolean flag = false;
public RabbitAndTurtle(String name){
super(name);
}
public void run(){
while(num if(flag){
break;
}
if(Thread.currentThread().getName().equals("rabbit")&&Math.random() num = num+2;
System.out.println(Thread.currentThread().getName()+"跑了"+num+"米");
}else if(Thread.currentThread().getName().equals("turtle")&&Math.random()>0.3){
num = num+1;
System.out.println(Thread.currentThread().getName()+"跑了"+num+"米");
}else{
Thread.yield();
}
}
//System.out.println("over");
if(!flag){
flag = true;
System.out.println(Thread.currentThread().getName()+"win!");
}

}

}
class Race{
public static void main(String[] args) {
RabbitAndTurtle t1 = new RabbitAndTurtle("turtle");
RabbitAndTurtle t2 = new RabbitAndTurtle("rabbit");
t1.start();
t2.start();
}
}
用了两次flag判断有什么用 麻烦详细一些 谢谢

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答