- 使用interrupt()打断
代码:public class CloseThread1 { public static void main(String[] args) { Thread thread = new Thread(() -> { try { Thread.sleep(10_1000);//模拟执行的任务 } catch (InterruptedException e) { System.out.println("任务强制结束!"); } }); thread.start(); //启动线程,执行任务 try { Thread.sleep(1000);//主线程等待任务执行1s thread.interrupt();//打断任务执行 } catch (InterruptedException e) { e.printStackTrace(); } } }
- 使用Thread.interrupted()优化异常处理:
代码:public class CloseThread2 { public static void main(String[] args) { Thread thread = new Thread(() -> { while (true) { //模拟任务 if (Thread.interrupted()) { System.out.println("任务强制结束!"); break; } } }); thread.start(); //启动线程,执行任务 try { Thread.sleep(1000);//主线程等待任务执行1s thread.interrupt();//打断任务执行 } catch (InterruptedException e) { e.printStackTrace(); } } }
- 使用daemon+join()+interrupt()制作限时结束
代码:public class CloseThread3 { //为了放在一起才使用的内部类 class ThreadService{ private Thread executor; //执行器 private boolean isFinish = false; //任务执行结束标志 public void execute(Runnable task) { executor = new Thread(() -> { Thread runner = new Thread(task); runner.setDaemon(true); //设置为守护线程 runner.start(); try { runner.join(); //等待任务执行完毕 isFinish = true; } catch (InterruptedException e) { System.out.println("任务强制结束!"); } }); executor.start(); } public Long shutdown(Long time) { long concurrentTime = System.currentTimeMillis(); while (!isFinish) { if (System.currentTimeMillis()-concurrentTime >= time) { System.out.println("任务超时!"); executor.interrupt(); break; } try { Thread.sleep(1); } catch (InterruptedException e) { System.out.println("执行线程被打断!"); } } return System.currentTimeMillis() - concurrentTime; } } public static void main(String[] args) { ThreadService service = new CloseThread3().new ThreadService(); service.execute(() ->{while (true){}}); //模拟任务执行 System.out.println("任务执行时间:" + service.shutdown(1000L)); } }
优雅的结束线程
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.