如何優雅的結束執行緒(二)
阿新 • • 發佈:2018-11-22
public class ThreadService { private Thread executeThread; private boolean finished = false; public void execute(Runnable task) { executeThread = new Thread() { @Override public void run() { Thread runner = new Thread(task); runner.setDaemon(true); runner.start(); try { runner.join(); finished = true; } catch (InterruptedException e) { //e.printStackTrace(); } } }; executeThread.start(); } public void shutdown(long mills) { long currentTime = System.currentTimeMillis(); while (!finished) { if ((System.currentTimeMillis() - currentTime) >= mills) { System.out.println("任務超時,需要結束他!"); executeThread.interrupt(); break; } try { executeThread.sleep(1); } catch (InterruptedException e) { System.out.println("執行執行緒被打斷!"); break; } } finished = false; } }
用到了執行緒中的守護執行緒和打斷,然後給執行緒一個時間,超時強制結束和正常結束