Thread.stop, Thread.suspend, Thread.resume 和Runtime.runFinalizersOnExit 這些終止線程運行的方法已經被廢棄,使用它們是極端不安全的!
1.線程正常執行完畢,正常結束
也就是讓run方法執行完畢,該線程就會正常結束。
但有時候線程是永遠無法結束的,比如while(true)。
2.監視某些條件,結束線程的不間斷運行
需要while()循環在某以特定條件下退出,最直接的辦法就是設一個boolean標誌,並通過設置這個標誌來控制循環是否退出。
public class ThreadFlag extends Thread { public volatile boolean exit = false; public void run() { while (!exit) { System.out.println("running!"); } } public static void main(String[] args) throws Exception { ThreadFlag thread = new ThreadFlag(); thread.start(); sleep(1147); // 主線程延遲5秒thread.exit = true; // 終止線程thread thread.join(); System.out.println("線程退出!"); }}3.使用interrupt方法終止線程
如果線程是阻塞的,則不能使用方法2來終止線程。
public class ThreadInterrupt extends Thread { public void run() { try { sleep(50000); // 延遲50秒} catch (InterruptedException e) { System.out.println(e.getMessage()); } } public static void main(String[] args) throws Exception { Thread thread = new ThreadInterrupt(); thread.start(); System.out.println("在50秒之內按任意鍵中斷線程!"); System.in.read(); thread.interrupt(); thread.join(); System.out.println("線程已經退出!"); }}以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。