前言
在多線程編程中會(huì)需要?jiǎng)討B(tài)創(chuàng)建線程來(lái)執(zhí)行任務(wù),在完成后釋放該線程,使用Excuotrs創(chuàng)建的線程,提供了shutDown方法進(jìn)行線程的關(guān)閉,但使用原生的Thread和Runable創(chuàng)建的線程池,其stop、destory方法都已經(jīng)被標(biāo)為Deprecate,那究竟該如何關(guān)閉線程?
實(shí)現(xiàn)邏輯
1、如果線程能正常執(zhí)行完,執(zhí)行結(jié)束后線程自動(dòng)關(guān)閉,無(wú)須特別處理
2、否則需要使用一個(gè)標(biāo)記如下running來(lái)控制并跳出線程循環(huán)執(zhí)行體,完成線程的自動(dòng)關(guān)閉
3、如果線程循環(huán)執(zhí)行體存儲(chǔ)阻塞,則在設(shè)置running變量,還需要通過(guò)interrupt中斷阻塞,使其能夠跳出線程循環(huán)執(zhí)行體,完成線程的自動(dòng)關(guān)閉。
下面是供參考的代碼邏輯:
public class BgpLsLinkMsgHandlerThread extends Thread { private volatile boolean running = true; @Override public void run() { while (running) { try { BgplsMsg message = queue.take(); bgpLsMsgHandler.handle(message); } catch (Exception e) { logger.error(“BgpLsLinkMsgHandlerThread handler exception.”, e); } } } public void handleMessage(BgplsMsg message) { try { queue.put(message); } catch (InterruptedException e) { logger.error(this, e); } } public int queueSize() { return queue.size(); } /** * 優(yōu)雅終止線程 */ public synchronized void termination() { this.running = false; this.interrupt(); }}
方法termination在修改標(biāo)記變量running后,調(diào)用了中斷函數(shù)interrupt,避免程序阻塞導(dǎo)致實(shí)際上并未關(guān)閉線程。