退出線程主要的思路是用一個標志位或者是使用線程的中斷方法
下面的例子是可以確保調用shutdown()方法,無論線程是否在休眠中,線程都會退出
public class ThreadTest extends Thread { private volatile boolean exit = false; @Override public void run() { while (!exit) { try { System.out.println("######"); Thread.sleep(10000); //休眠中了,shutdown(),會結束線程 System.out.println("^^^^^^^^^"); //正在執行這行代碼時,shutdown(),exit被修改為true了,退出循環了,線程結束 } catch (InterruptedException e) { exit = true; e.printStackTrace(); break; } } } public void shutdown() { exit = true; this.interrupt(); } public static void main(String[] args) throws InterruptedException { ThreadTest thread = new ThreadTest(); thread.start(); Thread.sleep(3000); thread.shutdown(); } }