Thread多线程样例--龟兔赛跑
Posted 肖帆咪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Thread多线程样例--龟兔赛跑相关的知识,希望对你有一定的参考价值。
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多线程样例--龟兔赛跑的主要内容,如果未能解决你的问题,请参考以下文章