一段模拟龟兔赛跑的多线程代码

原文地址: http://www.java2000.net/p10593
  1. /**
  2.  * 一段模拟龟兔赛跑的多线程代码。<br>
  3.  * 兔子比乌龟快5倍,但休息的时间长10倍。
  4.  * 
  5.  * @author 赵学庆,Java世纪网(java2000.net)
  6.  * 
  7.  */
  8. public class T {

  9.   public static void main(String[] args) {
  10.     TortoiseRace a = new TortoiseRace();
  11.     Thread runner1 = new Thread(a);
  12.     RabbitRace b = new RabbitRace();
  13.     Thread runner2 = new Thread(b);
  14.     runner1.start();
  15.     runner2.start();
  16.     while (ready < 2) {
  17.       try {
  18.         Thread.sleep(1);
  19.       } catch (InterruptedException e) {
  20.         e.printStackTrace();
  21.       }
  22.     }
  23.     synchronized (lock) {
  24.       lock.notifyAll();
  25.     }
  26.   }

  27.   static Object lock = new Object();
  28.   static int ready = 0;
  29. }

  30. class TortoiseRace implements Runnable {
  31.   public void run() {
  32.     synchronized (T.lock) {
  33.       T.ready++;
  34.       try {
  35.         T.lock.wait();
  36.       } catch (InterruptedException e1) {
  37.         e1.printStackTrace();
  38.       }
  39.     }
  40.     int TortoiseDistance = 0;
  41.     for (int i = 0; TortoiseDistance <= 1000; i++) {
  42.       TortoiseDistance++;
  43.       System.out.println("乌龟跑了1米!");
  44.       try {
  45.         Thread.sleep(1);
  46.       } catch (InterruptedException e) {
  47.       }
  48.     }
  49.     System.out.println("乌龟已经跑完了比赛路程!");

  50.   }
  51. }

  52. class RabbitRace implements Runnable {
  53.   public void run() {
  54.     T.ready++;
  55.     synchronized (T.lock) {
  56.       try {
  57.         T.lock.wait();
  58.       } catch (InterruptedException e1) {
  59.         e1.printStackTrace();
  60.       }
  61.     }
  62.     int RabbitDistance = 0;
  63.     for (int j = 0; RabbitDistance <= 1000; j++) {
  64.       RabbitDistance += 5;
  65.       System.out.println("兔子跑了5米!");
  66.       try {
  67.         Thread.sleep(10);
  68.       } catch (InterruptedException e) {
  69.       }
  70.     }
  71.     System.out.println("兔子跑完了比赛路程!");

  72.   }
  73. }

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值