程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 一段模擬龜兔賽跑的多線程代碼

一段模擬龜兔賽跑的多線程代碼

編輯:關於JAVA

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.sleep (10);
      } catch (InterruptedException e) {
      }
    }
    System.out.println("兔子跑完了比賽路程!");

  }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved