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

/**  
 * 一段模拟龟兔赛跑的多线程程序。 
 * 兔子比乌龟快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.sleep(10);   
      } catch (InterruptedException e) {   
      }   
    }   
    System.out.println(兔子跑完了比赛路程!);   
  
  }   
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值