指定次数或者条件 停止定时任务线程

1.定义线程池,我是在@PostConstruct中进行初始化的

@Slf4j
public class CommonScheduledThreadPool {
    /**
     * 自定义线程池
     */
    public static ScheduledThreadPoolExecutor spool;

    public static void init() {
        spool = new ScheduledThreadPoolExecutor(2);
    }
}

2.先创建一个TASK用于执行定时任务,

4.然后在线程内部判断CountDownLatch 是否完成,完成时从map获取外部传入的futrue,然后cancel取消任务。

@Slf4j
public class InitVisitorEntityTask implements Runnable {
    private VisitorEntityService visitorEntityService;
    private ConcurrentHashMap futuremap;
    private volatile CountDownLatch cdl;
    private AtomicInteger ait = new AtomicInteger(0);

    public InitVisitorEntityTask(ConcurrentHashMap futuremap,VisitorEntityService visitorEntityService,CountDownLatch cdl) {
        this.futuremap = futuremap;
        this.visitorEntityService = visitorEntityService;
        this.cdl = cdl;
    }

    @Override
    public void run() {
        log.info("调用初始化流程");
        cdl.countDown();
        visitorEntityService.init();
        log.info("初始化完成第【{}】个流程!",ait.incrementAndGet());
        if(cdl.getCount()==0){
            log.info("所有流程创建完成,准备销毁定时任务!");
            Future future = futuremap.get("future");
            future.cancel(true);
        }

    }
}

 

3.下面是使用主流程,先定义一个future,放到map中(带入到线程中),线程池返回结果用刚才定义的future接收。

 //用于判断结束定时任务
        ConcurrentHashMap futuremap = new ConcurrentHashMap();
        InitVisitorEntityTask ivet = new InitVisitorEntityTask(futuremap,visitorEntityService,cdl);
        Future future = CommonScheduledThreadPool.spool.scheduleAtFixedRate(ivet, 0, per_msec_vs_count, TimeUnit.MILLISECONDS);
        futuremap.put("future",future);

 

你可能感兴趣的:(学习笔记)