1.問題
當我們認為某個任務執行時間太長了,想要停止這個任務,在線程池里應該如何實現呢?
2.不用線程池如何停止一個線程
停止線程池里的任務等同於停止一個線程,所以我們需要先了解如何停止一個線程。
網上很多博客寫了停止一個線程解決方法,停止一個線程有三種方法。
2.1使用標識
示例:
static volatile boolean flag = true; public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Runnable() { @Override public void run() { try { while (flag) { Thread.sleep(1000); System.err.println("print a"); } } catch (InterruptedException e) { System.err.println("我是在sleep interrupted"); } } }, "t1"); thread.start(); Thread.sleep(5000); flag = false; }
注意使用volatile關鍵字
2.2使用stop
作廢,不用關心了
2.3使用interrupt
示例:
public static void main(String[] args) throws Exception { Thread thread = new Thread(new Runnable() { @Override public void run() { try { while (true) { Thread.sleep(1000); //寫了sleep就不用寫下面的判斷 if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } System.err.println("print a"); } } catch (InterruptedException e) { e.printStackTrace(); } } }, "t1"); thread.start(); Thread.sleep(20); thread.interrupt(); }
3.停止線程池里的任務
按照停止線程方法,停止線程池里的任務有兩種方法(stop作廢)
3.1使用標識
這兒不貼代碼了,思路比較簡單,使用全局的Map存任務名與是否停止,在任務里判斷。
3.2使用interrupt
示例:
public class ThreadPoolStopThread { static class MyRunnable implements Runnable { private String jobName; private Thread nowThread; MyRunnable(String jobName) { this.jobName = jobName; } public void setInterrupted() { nowThread.interrupt(); } @Override public void run() { nowThread = Thread.currentThread(); try { while (true) { Thread.sleep(1000); // 寫了sleep就不用再判斷isInterrupted()了 System.err.println("當前線程:" + Thread.currentThread().getName() + " 當前任務:" + jobName); } } catch (InterruptedException e) { System.err.println("當前線程:" + Thread.currentThread().getName() + " 當前任務:" + jobName + "馬上停止"); e.printStackTrace(); } } } public static void main(String[] args) throws InterruptedException { ExecutorService es = Executors.newFixedThreadPool(2, new MyThreadFactory()); MyRunnable job1 = new MyRunnable("job-1"); MyRunnable job2 = new MyRunnable("job-2"); MyRunnable job3 = new MyRunnable("job-3"); es.execute(job1); es.execute(job2); es.execute(job3); System.err.println("5s后停止job-1"); Thread.sleep(5000); job1.setInterrupted(); } }