ScheduledExecutorService 根据条件终止调度任务

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 futureMap = new ConcurrentHashMap();
		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 futureMap;
		private int count = 0;
		private String jobId;

		public JobTest(String jobId,ConcurrentHashMap 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 getFutureMap() {
			return futureMap;
		}

		public void setFutureMap(ConcurrentHashMap futureMap) {
			this.futureMap = futureMap;
		}

		public String getJobId() {
			return jobId;
		}

		public void setJobId(String jobId) {
			this.jobId = jobId;
		}

}

你可能感兴趣的:(java,开发技巧)