Java 中所有執行緒都必須實現哪種方法?


建立執行緒類時,我們必須覆蓋Thread 類的run() 方法。此方法為執行緒提供了一個入口點,您將把自己的完整業務邏輯放入此方法中。

舉例

class ThreadDemo extends Thread {
   private String threadName;

   ThreadDemo( String name) {
      threadName = name;
      System.out.println("Creating " +        threadName );
   }

   public void run() {
      System.out.println("Running " +          threadName );
      try {
         for(int i = 4; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
           
            // Let the thread sleep for a while.
            Thread.sleep(50);
         }
      } catch (InterruptedException e) {
         System.out.println("Thread " +      threadName + " interrupted.");
      }
      System.out.println("Thread " +     threadName + " exiting.");
   }
}

public class TestThread {
   public static void main(String args[]) {
      ThreadDemo T1 = new ThreadDemo( "Thread-1");
      T1.start();
      ThreadDemo T2 = new ThreadDemo( "Thread-2");
      T2.start();
   }
}

輸出

Creating Thread-1
Creating Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

更新於:2020 年 2 月 25 日

1K+ 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.