Java龟兔接替赛

 要求:
1. 用两个线程分别模拟乌龟和兔子奔跑。兔子和乌龟的速度不同。
2. 两个线程共同跑完总长1000米。
3. 同一时间只能有一个在跑,另一个处于休息状态。
4. 当总长度跑完以后,两个线程结束。
5. 当两个线程都结束后,打印"到达终点"。
6. 分别输出乌龟和兔子奔跑的距离。

package com.lanou.lock;

import java.util.concurrent.locks.ReentrantLock;

public class Turtle implements Runnable {
	static ReentrantLock lock = new ReentrantLock();
	static int i = 1;
	static int turtle1 = 0;
	static int rabbit1 = 0;

	public static void main(String[] args) {
		Object key = new Object();
		Turtle turtle = new Turtle();
		Thread thread = new Thread(turtle, "兔");
		Thread thread1 = new Thread(turtle, "龟");
		thread.start();
		thread1.start();
		
		try {
			thread.join();
			thread1.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
			System.out.println("接力赛完成" + "兔跑了" + rabbit1 + "米" + " 龟跑了" + turtle1 + "米");	
	}

	@Override
	public void run() {

		try {

			Thread.sleep(10);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		rabbit();
	}

	public void rabbit() {
		boolean flag = true;
		while (true) {
			synchronized (Turtle.class) {
				if (i > 100) {
					flag = false;					
					break;
				}
				try {
					if (Thread.currentThread().getName().equals("兔") ) {
						rabbit1++;
						Thread.sleep(10);
					} else {
						turtle1++;
						Thread.sleep(30);
					}
					printMsg("跑了第" + (i++) + "米");
					this.notify();
					this.wait();// 让当前持有锁的线程等待
					this.notify();
				} catch (Exception e) {
				}
			}
			try {
				if (Thread.currentThread().getName().equals("兔") ) {
					Thread.sleep(10);
				} else {
					
					Thread.sleep(45);
				}
				
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void printMsg(String msg) {
		System.out.println("[" + Thread.currentThread().getName() + "]" + msg);
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值