Java中終止線程的三種方法
Thread.stop, Thread.suspend, Thread.resume 和Runtime.runFinalizersOnExit 這些終止線程運行的方法已經被廢棄,使用它們是極端不安全的!
1.線程正常執(zhí)行完畢,正常結束
也就是讓run方法執(zhí)行完畢,該線程就會正常結束。
但有時候線程是永遠無法結束的,比如while(true)。
2.監(jiān)視某些條件,結束線程的不間斷運行
需要while()循環(huán)在某以特定條件下退出,最直接的辦法就是設一個boolean標志,并通過設置這個標志來控制循環(huán)是否退出。
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("線程已經退出!"); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
使用注解@Recover優(yōu)化丑陋的循環(huán)詳解
我們知道在實現(xiàn)一個功能的時候是可以使用不同的代碼來實現(xiàn)的,那么相應的不同實現(xiàn)方法的性能肯定也是有差別的,下面這篇文章主要給大家介紹了關于使用注解@Recover優(yōu)化丑陋的循環(huán)的相關資料,需要的朋友可以參考下2022-04-04IDEA中application.properties的圖標顯示不正常的問題及解決方法
這篇文章主要介紹了IDEA中application.properties的圖標顯示不正常的問題及解決方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04