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秒打印一次

ScheduledThreadPoolExecutor是一个具有延迟任务和定期任务功能的线程池执行器。它是ThreadPoolExecutor的一个子类,并且可以通过设置延迟时间和周期时间来执行任务。 以下是一个示例代码,展示了如何使用ScheduledThreadPoolExecutor: import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ScheduleThreadPoolExecutorTest { public static void main(String[] args) { ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5); executor.schedule(new Runnable() { @Override public void run() { System.out.println("执行任务"); } }, 2, TimeUnit.SECONDS); executor.shutdown(); } } 在这个示例中,我们创建了一个ScheduledThreadPoolExecutor对象,并设置了最大核心线程数为5。然后,我们调用schedule方法来添加一个延迟任务。任务将在2秒后执行。最后,我们调用shutdown方法来关闭线程池。 另外,还有一个使用scheduleWithFixedDelay方法的示例代码: import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ScheduleThreadPoolExecutorTest { public static void main(String[] args) { ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(100); executor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { System.out.println("打印当前时间"); try { Thread.sleep(1000); //制造异常 int i = 2 / 0; } catch (InterruptedException e) { e.printStackTrace(); } } }, 2, 1, TimeUnit.SECONDS); } } 在这个示例中,我们使用scheduleWithFixedDelay方法来添加一个周期任务。任务将在2秒后开始执行,并且每隔1秒执行一次。在任务的run方法中,我们打印当前时间,并且制造了一个异常。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值