赞
踩
使用ScheduledExecutorService.schedule提交任务到执行器定时执行后,我们想在某一特定条件下终止执行器中的某个任务。本文列举2种实现方法。
import java.util.concurrent.*; /** * @author bigbird * @Description: ${描述} */ public class Test { public static void main(String[] args) throws Exception { ConcurrentHashMap<String, ScheduledFuture> taskMap = new ConcurrentHashMap<>(4); ScheduledExecutorService scheduleExecutor = new ScheduledThreadPoolExecutor(3); ScheduledFuture scheduledFutureI = scheduleExecutor.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("--------------------------------"); for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName() + ",i=" + i); } } }, 1, 2, TimeUnit.SECONDS); taskMap.put("scheduledFutureI", scheduledFutureI); ScheduledFuture scheduledFutureJ = scheduleExecutor.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("--------------------------------"); for (int j = 0; j < 10; j++) { if (j == 3) { //方式1:通过在任务内部抛出异常的方式终止任务 System.out.println("scheduledFuture2终止..."); throw new RuntimeException(); } System.out.println(Thread.currentThread().getName() + ",j=" + j); } } }, 1, 2, TimeUnit.SECONDS); taskMap.put("scheduledFutureJ", scheduledFutureJ); ScheduledFuture scheduledFutureK = scheduleExecutor.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("--------------------------------"); for (int k = 0; k < 10; k++) { if (k == 6) { //方式2:通过cancel方式终止任务 System.out.println("scheduledFuture3终止..."); taskMap.get("scheduledFuture3").cancel(true); } System.out.println(Thread.currentThread().getName() + ",k=" + k); } } }, 1, 1, TimeUnit.SECONDS); taskMap.put("scheduledFutureK", scheduledFutureK); Thread.sleep(10000); //如果注释下面一行,scheduleExecutor不被shutdown,则scheduledFutureI将一直被执行 scheduleExecutor.shutdown(); System.out.println("主线程终止 " + Thread.currentThread().getName() + ",调度器关闭"); //运行该程序,可以发现scheduledFutureJ和scheduledFutureK分别在特定条件下使用了不同的方式终止执行,scheduledFutureI一直正常运行,直到scheduleExecutor被shutdown } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。