赞
踩
线程池定时任务条件取消
使用的方法是scheduleAtFixedRate
重写run方法,delay10秒后开始,每重复任务
取消的话使用的方法是设置volatile变量flag,当符合取消的条件后将flag置为true
private volatile boolean flag = false;
ConcurrentHashMap<String, ScheduledFuture> taskMap = new ConcurrentHashMap<>(1);
ScheduledExecutorService scheduleExecutor = new ScheduledThreadPoolExecutor(1);
ScheduledFuture scheduledFuture = scheduleExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
if (getDownloadURL(taskId, accessToken) != null) {
//方式2:通过cancel方式终止任务
System.out.println("终止...");
flag = true;
taskMap.get("scheduledFuture").cancel(true);
// System.out.println("downloadURL:"+downloadURL);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}, 10, 30, TimeUnit.SECONDS);
taskMap.put("scheduledFuture", scheduledFuture);
while(!flag){
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。