我們可以在 Java 中直接呼叫 run() 方法而不是 start() 嗎?


是的,我們可以做到。讓我們看一個示例 -

示例

 即時演示

class my_thread extends Thread{
   public void run(){
      try{
         System.out.println ("The thread " + Thread.currentThread().getId() + " is currently running");
      }
      catch (Exception e){
         System.out.println ("The exception has been caught");
      }
   }
}
public class Main{
   public static void main(String[] args){
      int n = 6;
      for (int i=1; i<n; i++){
         my_thread my_object = new my_thread();
         my_object.run();
      }
   }
}

輸出

The thread 1 is currently running
The thread 1 is currently running
The thread 1 is currently running
The thread 1 is currently running
The thread 1 is currently running

一個名為“my_thread”的類繼承了主執行緒,其中定義了一個“run”函式,該函式給出正在執行的當前執行緒的 ID。定義了一個 try and catch 塊,該塊捕獲異常(如果有)並顯示相關的錯誤。在主函式中,執行一個“for”迴圈並建立“my_thread”類的新的物件。針對此物件呼叫“run”函式。

更新於:14-7-2020

341 次瀏覽

開啟你的 職業

透過完成該課程獲得認證

開始
廣告
© . All rights reserved.