package cc.lanou.test;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Race implements Callable<Integer> {
/**
* 用两个线程模拟龟兔赛跑 要求: 1. 设计两个线程,一个表示完成乌龟跑的过程,另一个线程模拟兔子跑的过程 2. 乌龟和兔子都跑相同的距离 3.
* 在乌龟和兔子线程中,每跑一段距离,比如1/10总距离,就输出XX跑了多少米,离终点还有多远 4. 乌龟和兔子在到达终点后,分别输出提示,到达终点。 5.
* 兔子在跑到某段距离后可以让其睡一会,模拟真实的龟兔赛跑(不做要求)
*
* @param args
* @throws ExecutionException
* @throws InterruptedException
*/
static int i2 = 0;
public static void main(String[] args) throws InterruptedException, ExecutionException {
Race race = new Race();
FutureTask<Integer> ft = new FutureTask<Integer>(race);
Thread thread = new Thread(ft, "兔");
Race race1 = new Race();
FutureTask<Integer> ft1 = new FutureTask<Integer>(race1);
Thread thread1 = new Thread(ft1, "龟");
thread.start();
thread1.start();
}
//胜利
private static void victory(int distance) {
if (distance == 0) {
// Thread.currentThread().getName();
if(i2 == 0){
i2++;
System.out.println("胜利者是"+ Thread.currentThread().getName());
//System.out.println(i);
} else if(i2 == 1){
System.out.println("失败者是"+ Thread.currentThread().getName());
}
}
}
@Override
public Integer call() throws Exception {
int i = 1;
int residue = 100;
int ranInt = random.nextInt(3);
for (; i <= 100; i++) {
// Thread.sleep(100);
if (( i % 50 == 0) && Thread.currentThread().getName().equals("兔")) {
System.out.println("兔子偷懒了,睡起来了");
Thread.sleep(10);
}
residue--;
if (i == 100) {
System.out.println(Thread.currentThread().getName() + "到终点了");
} else if(residue % 10 == 0){
System.out.println(Thread.currentThread().getName() + "跑了" + i + "米" + " 终点剩余" + residue + " 米");
} else {
System.out.println(Thread.currentThread().getName() + "跑了" + i + "米");
}
victory(residue);
}
return residue;
}
}