当前位置:   article > 正文

jdk 1.8 之 ScheduledThreadPoolExecutor 定时任务的退出和取消_scheduledthreadpoolexecutor 条件判断结束任务

scheduledthreadpoolexecutor 条件判断结束任务
package com.dosrain.shunc.trial.schedule;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.*;

public class PoolTest2 {

    public static void main(String[] args) {

        // 设置一个同步计算数,目的是让子线程完成工作后,主线程再继续工作。
        // 因为这里只有一个子线程,所以设值为 1
        CountDownLatch countDownLatch = new CountDownLatch(1);

        // 创建线程池
        ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(1);

        // 创建固定时延的定时任务
        ScheduledFuture<?> scheduledFuture = pool.scheduleWithFixedDelay(
                new Task2(countDownLatch, 10)
                , 0
                , 2, TimeUnit.SECONDS);

        try {
            // 暂停主线程,等待同步计算数器归零后,主线程再继续工作
            countDownLatch.await();
            // 同步计数器已归零,说明定时任务已满足条件退出
            // 所以取消定时任务
            scheduledFuture.cancel(true);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 关闭线程池
        pool.shutdown();
    }
}

class Task2 implements Runnable {

    CountDownLatch countDownLatch;
    private int counter;

    public Task2(CountDownLatch countDownLatch, int counter) {
        this.countDownLatch = countDownLatch;
        this.counter = counter;
    }

    @Override
    public void run() {
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 处理一些任务
        System.out.println(localDateTime.format(dtf) + " [" + Thread.currentThread().getName() + "] " + counter);

        if (counter-- == 0) {
            // 判断达到停止任务的条件
            countDownLatch.countDown();
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63

程序执行结果:
2020-07-13 15:37:54 [pool-1-thread-1] 10
2020-07-13 15:37:56 [pool-1-thread-1] 9
2020-07-13 15:37:58 [pool-1-thread-1] 8
2020-07-13 15:38:00 [pool-1-thread-1] 7
2020-07-13 15:38:02 [pool-1-thread-1] 6
2020-07-13 15:38:04 [pool-1-thread-1] 5
2020-07-13 15:38:06 [pool-1-thread-1] 4
2020-07-13 15:38:08 [pool-1-thread-1] 3
2020-07-13 15:38:10 [pool-1-thread-1] 2
2020-07-13 15:38:12 [pool-1-thread-1] 1
2020-07-13 15:38:14 [pool-1-thread-1] 0

Process finished with exit code 0

要注意到是2秒打印一次

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/83672
推荐阅读
相关标签
  

闽ICP备14008679号