直接给代码
public static void main(String[] arg0) throws Exception {
final Map<String, Future> futures = new HashMap<>();
final String jobID = "startJob";
final CountDownLatch countDownLatch = new CountDownLatch(1);
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
Future future = service.scheduleAtFixedRate(new Runnable(){
private int count;
@Override
public void run() {
count++;
System.out.println("第"+count+"次开始执行任务");
if (count == 2){ //取消任务
Future future = futures.get(jobID);
if (future != null){
future.cancel(true);
}
countDownLatch.countDown();
System.out.println("任务停止");
}
}
},3000,1000, TimeUnit.MILLISECONDS);
futures.put(jobID, future);
countDownLatch.await();
service.shutdown();
}