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”。
廣告