線程實例一

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

  public void run() {
    while (true)
    {
      try
      {
        Thread.sleep(2000);
      }
      catch (InterruptedException e)
      {
        System.out.println("Interrupted");
      }
      System.out.println("線程" + threadNum + ",計數:" + i);
      if (--i == 0)
        return;
    }
  }
  public static void main(String[] args) {
    //依次建立5個線程
    for (int i = 0; i <= 5; i++)
    {
      new ThreadTest(i).start();
    }
  }
}

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