線程實例二

public class RunnableTest
    implements Runnable {
  public static void main(String[] args) {
    for (int i = 0; i <= 5; i++) {
      //使用Runnable接口的類,必須手工創建一個線程
      new Thread(new RunnableTest(i)).start();
    }
  }

  private static int threadCount = 0;
  private int threadNum;
  private int i = 5;
  //Runnable的構造函數,每次執行線程計數器threadCount加一
  public RunnableTest(int threadNo) {
    threadNum = threadNo;
    threadCount++;
    System.out.println("創建線程" + threadNum);
  }

  public void run() {
    while (true) {
      try {
        Thread.sleep(100);
      }
      catch (InterruptedException e) {
        System.out.println("Interrupted");
      }
      System.out.println("線程" + threadNum + " ,計數" + i);
      if (--i == 0)
        return;
    }
  }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章