Java 中中止執行緒


範例

 即時演示

public class Main{
   static volatile boolean exit = false;
   public static void main(String[] args){
      System.out.println("Starting the main thread");
      new Thread(){
         public void run(){
            System.out.println("Starting the inner thread");
            while (!exit){
            }
            System.out.println("Exiting the inner thread");
         }
      }.start();
      try{
         Thread.sleep(100);
      }
      catch (InterruptedException e){
         System.out.println("Exception caught :" + e);
      }
      exit = true;
      System.out.println("Exiting main thread");
   }
}

輸出

Starting the main thread
Starting the inner thread
Exiting main thread
Exiting the inner thread

主類建立一個新執行緒,並呼叫它的“run”函式。在此,定義了一個名為“exit”的布林值,最初設定為 false。在 while 迴圈外部,呼叫了“start”函式。在 try 塊中,新建立的執行緒休眠特定時間,此後會捕獲異常,並且相關訊息會顯示在螢幕上。在此之後,主執行緒將退出,因為 exit 的值將設定為“true”。

更新於:2020 年 7 月 14 日

286 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告