要求:
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);
}
}