赞
踩
- package com.taobao.vcloud.scheduler.job;
-
- import java.util.concurrent.ConcurrentHashMap;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.TimeUnit;
-
- public class ConditionCancelScheduler {
-
- public static void main(String[] args) throws Exception {
-
- ConcurrentHashMap<String, Future> futureMap = new ConcurrentHashMap<String, Future>();
- ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
-
- JobTest job_1 = new JobTest("job_1", futureMap);
-
- Future future = scheduler.scheduleAtFixedRate(job_1, 1, 5, TimeUnit.SECONDS);
- futureMap.put(job_1.getJobId(), future);
- //Thread.sleep(10000);
- JobTest job_2 = new JobTest("job_22", futureMap);
-
- Future future_2 = scheduler.scheduleAtFixedRate(job_2, 1, 5, TimeUnit.SECONDS);
- futureMap.put(job_2.getJobId(), future_2);
- Thread.sleep(20000);
-
- System.out.println("test over");
- scheduler.shutdown();
- }
- }
- public class JobTest implements Runnable {
- private ConcurrentHashMap<String, Future> futureMap;
- private int count = 0;
- private String jobId;
-
- public JobTest(String jobId,ConcurrentHashMap<String, Future> futureMap){
- this.jobId = jobId;
- this.futureMap = futureMap;
- }
- @Override
- public void run() {
- count++;
- System.out.println("this is " + count);
-
- if (count > 1) {
- try {
- Future future = futureMap.remove(jobId);
-
- future.cancel(true);
- } finally {
- System.out.println("jobId "+jobId +"had cancel");
- }
- }
-
- }
-
- public ConcurrentHashMap<String, Future> getFutureMap() {
- return futureMap;
- }
-
- public void setFutureMap(ConcurrentHashMap<String, Future> futureMap) {
- this.futureMap = futureMap;
- }
-
- public String getJobId() {
- return jobId;
- }
-
- public void setJobId(String jobId) {
- this.jobId = jobId;
- }
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。