一段模拟龟兔竞走的多线程代码[网络技术]
本文“一段模拟龟兔竞走的多线程代码[网络技术]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
根源:豆豆网
Java代码
/**
* 一段模拟龟兔竞走的多线程程序.<br>
* 兔子比乌龟快5倍,但歇息的时间长10倍.
*
* @author 赵学庆,Java世纪网(java2000.net)
*
*/
public class T {
public static void main(String[] args) {
TortoiseRace a = new TortoiseRace();
Thread runner1 = new Thread(a);
RabbitRace b = new RabbitRace();
Thread runner2 = new Thread(b);
runner1.start();
runner2.start();
while (ready < 2) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (lock) {
lock.notifyAll();
}
}
static Object lock = new Object();
static int ready = 0;
}
class TortoiseRace implements Runnable {
public void run() {
synchronized (T.lock) {
T.ready++;
try {
T.lock.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
int TortoiseDistance = 0;
for (int i = 0; TortoiseDistance <= 1000; i++) {
TortoiseDistance++;
System.out.println("乌龟跑了1米!");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
System.out.println("乌龟已经跑完了比赛路途!");
}
}
class RabbitRace implements Runnable {
public void run() {
T.ready++;
synchronized (T.lock) {
try {
T.lock.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
int RabbitDistance = 0;
for (int j = 0; RabbitDistance <= 1000; j++) {
RabbitDistance += 5;
System.out.println("兔子跑了5米!");
try {
Thread.s
以上是“一段模拟龟兔竞走的多线程代码[网络技术]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |