jdk 1.8 之 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();
        }
    }
}

程序执行结果:
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秒打印一次

你可能感兴趣的:(开船,多线程)