徹底停止運行線程池ThreadPoolExecutor

來源:互聯網
上載者:User

最近系統開發時遇到這樣一個需求:

該功能執行時間很久,如果運行過程出現錯誤,也無法將其停止,必須眼睜睜的看著它浪費很久時間,除非停止伺服器。

於是,我就想著如何給該功能加上一個“停止”的功能呢。

經過不斷的思考和測試,發現思路如此簡單,直接上代碼。

package com.iamzken.test;import java.util.ArrayList;import java.util.List;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;public class ThreadPoolExecutorTest {//線程池private static ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 5, 5,TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10),new ThreadPoolExecutor.CallerRunsPolicy());//定義一個線程,相當於父線程private static Thread t;//儲存線程池中當前所有正在執行任務的活動線程,相當於子線程private static List<Thread> activeThreads = new ArrayList<Thread>(5);//根據參數b的值,決定是啟動線程還是停止線程public static void test(boolean b) {if (b) {System.out.println("start========================================");//停止父線程,這裡使用了Thread類的暴力停止方法stopt.stop();//遍曆並停止所有子線程,這裡使用了Thread類的暴力停止方法stop//這裡一定要把子線程也停止掉,原來以為停止了父線程,子線程就會自動停止,事實證明這是錯誤的,必須在停止父線程的同時停止掉子線程才能徹底停止掉整個線程for (int i = 0; i < activeThreads.size(); i++) {Thread t = activeThreads.get(i);System.out.println(t.getName());t.stop();}System.out.println("stop==========================================");} else {//建立父線程t = new Thread() {@Overridepublic void run() {//建立線程池要執行的兩個任務r1和r2。這兩個任務都是死迴圈Runnable r1 = new Thread() {@Overridepublic void run() {Thread currentThread = Thread.currentThread();activeThreads.add(currentThread);int i = 1;while (true) {System.out.println(currentThread.getName()+"------------>"+(i++));try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}};Runnable r2 = new Thread() {@Overridepublic void run() {Thread currentThread = Thread.currentThread();activeThreads.add(currentThread);int i = 1;while (true) {System.out.println(currentThread.getName()+"------------>"+(i++));try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}};//線上程池中執行兩個任務r1和r2,實際上相當於在t中開啟了兩個子線程,而兩個子線程由線程池維護而已pool.execute(r1);pool.execute(r2);};};//啟動父線程t.start();}}//測試方法public static void main(String[] args) {//傳入false代表要啟動線程執行任務test(false);try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}//執行任務5秒之後,傳入false代表要停止線程test(true);}}


原來以為停止了父線程,子線程就會自動停止,事實證明這是錯誤的,必須在停止父線程的同時停止掉子線程才能徹底停止掉整個線程。
另:停止線程我使用了Thread類中的暴力停止方法stop,因為其他方法都不徹底,如有其他更好的方法,朋友們可以及時與我交流。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.