趣味编程:一段模拟龟兔赛跑的多线程代码

     Java代码  
 /**
  * 段模拟龟兔赛跑多线程

  * 兔子比乌龟快5倍但休息时间长10倍
  *
  * @author 赵学庆Java世纪网(java2000.net)
  *
  */
  public  T {
  public  void (String args) {
  TortoiseRace a =  TortoiseRace;
  Thread runner1 =  Thread(a);
  RabbitRace b =  RabbitRace;
  Thread runner2 =  Thread(b);
  runner1.start;
  runner2.start;
  while (ready < 2) {
  try {
  Thread.sleep(1);
  } catch (InterruptedException e) {
  e.prStackTrace;
  }
  }
  synchronized (lock) {
  lock.notyAll;
  }
  }
   Object lock =  Object;
    ready = 0;
  }
   TortoiseRace implements Runnable {
  public void run {
  synchronized (T.lock) {
  T.ready;
  try {
  T.lock.wait;
  } catch (InterruptedException e1) {
  e1.prStackTrace;
  }
  }
   TortoiseDistance = 0;
  for ( i = 0; TortoiseDistance <= 1000; i) {
  TortoiseDistance;
  .out.prln("乌龟跑了1米!");
  try {
  Thread.sleep(1);
  } catch (InterruptedException e) {
  }
  }
  .out.prln("乌龟已经跑完了比赛路程!");
  }
  }
   RabbitRace implements Runnable {
  public void run {
  T.ready;
  synchronized (T.lock) {
  try {
  T.lock.wait;
  } catch (InterruptedException e1) {
  e1.prStackTrace;
  }
  }
   RabbitDistance = 0;
  for ( j = 0; RabbitDistance <= 1000; j) {
  RabbitDistance  5;
  .out.prln("兔子跑了5米!");
  try {
  Thread.sleep(10);
  } catch (InterruptedException e) {
  }
  }
  .out.prln("兔子跑完了比赛路程!");
  }
  }



Tags: 

延伸阅读

最新评论

发表评论