java安全停止線程的方法詳解
更新時間:2019年10月11日 10:33:20 作者:MartinEDM
這篇文章主要介紹了java安全停止線程的方法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
Thread.stop()是一個被廢棄的方法,不被推薦使用的原因是stop方法太過于暴力,強行把執(zhí)行到一半的線程終止,并且會立即釋放這個線程所有的鎖。會破壞了線程中引用對象的一致性。
使用判斷標(biāo)志位的方法中斷線程
- interrupt() //線程中斷 (標(biāo)志位設(shè)置為true)
- isInterrupted() //判斷是否被中斷
- interrupted() //判斷是否中斷,并清除當(dāng)前中斷狀態(tài)(標(biāo)志位改為false)
public static class TestThread extends Thread{ public TestThread(String name){ super(name); } @Override public void run() { String threadName=Thread.currentThread().getName(); while (!isInterrupted()){ //Runnable中用 Thread.currentThread().isInterruputed System.out.println(threadName+" is run"); } System.out.println(threadName+" flag is "+isInterrupted()); } } public static void main(String[] args) throws InterruptedException { Thread testThread=new TestThread("test"); testThread.start(); Thread.sleep(2000); testThread.interrupt(); }
當(dāng)拋出 InterruptedException 異常,線程中斷標(biāo)志位會被復(fù)位 false, 線程不會正常中斷 ,需要手動中斷interrupt()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解讀SpringBoot接收List<Bean>參數(shù)問題(POST請求方式)
這篇文章主要介紹了解讀SpringBoot接收List<Bean>參數(shù)問題(POST請求方式),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09java抓取鼠標(biāo)事件和鼠標(biāo)滾輪事件示例
這篇文章主要介紹了java抓取鼠標(biāo)事件和鼠標(biāo)滾輪事件示例,需要的朋友可以參考下2014-05-05