Java线程模拟龟兔赛跑

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;
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值