jdk定时器使用Timer VS ScheduledExecutorService

定时器-单线程VS多线程

1、目标:根据某个标记状态或者任务都执行完成后,停止定时任务
开发环境:idea、jdk11

2、单线程方式

public static void main(String[] args) {
    Stopwatch sw = Stopwatch.createStarted();
    // 默认状态为true
    AtomicBoolean flag = new AtomicBoolean(true);
    var t1 = new Thread(() -> {
        try {
            System.out.println(flag + Thread.currentThread().getName());
            Thread.sleep(1000);
            System.out.println(flag + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }, "t1");
    var t2 = new Thread(() -> {
        try {
            Thread.sleep(1200);
            // 改为false,其他任务也无需执行
            flag.set(false);
        } catch (InterruptedException e) {
           // e.printStackTrace();
           // Thread.currentThread().interrupt();
        }
    }, "t2");
    var t3 = new Thread(() -> {
        try {
            System.out.println(flag + Thread.currentThread().getName());
            Thread.sleep(5000);
            System.out.println(flag + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }, "t3");
    t1.start();
    t2.start();
    t3.start();

    Timer timer = new Timer();
    // 同步器设置计数为1
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            System.out.println("单线程定时器轮询");
            if (!flag.get()) {
                // 满足条件,计数清零
                countDownLatch.countDown();
                System.out.println("标记改变,结束定时器");
            } else if (!t1.isAlive() && !t2.isAlive() && !t3.isAlive()) {
            // 满足条件,计数清零
                countDownLatch.countDown();
                System.out.println("线程执行完成,结束定时器,查看标记状态" + flag.get());
            }
        }
    }, 0, 300);
    try {
        System.out.println("countDownLatch wait");
        countDownLatch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
        Thread.currentThread().interrupt();
    }
    // 关闭定时器
    timer.cancel();
    // 清空队列
    timer.purge();
    sw.stop();
    log.info(String.valueOf(sw.elapsed(TimeUnit.MILLISECONDS)));

}

3、多线程方式

public static void main(String[] args) {
    Stopwatch sw = Stopwatch.createStarted();
    AtomicBoolean flag = new AtomicBoolean(true);
    var t1 = new Thread(() -> {
        try {
            System.out.println(flag + Thread.currentThread().getName());
            Thread.sleep(1000);
            System.out.println(flag + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }, "t1");
    var t2 = new Thread(() -> {
        try {
            Thread.sleep(1200);
            flag.set(false);
        } catch (InterruptedException e) {
           // e.printStackTrace();
           // Thread.currentThread().interrupt();
        }
    }, "t2");
    var t3 = new Thread(() -> {
        try {
            System.out.println(flag + Thread.currentThread().getName());
            Thread.sleep(5000);
            System.out.println(flag + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }, "t3");
    t1.start();
    t2.start();
    t3.start();
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    final var job = "job";
    final Map<String, ScheduledFuture<?>> futures = new HashMap<>(1);

    final CountDownLatch countDownLatch = new CountDownLatch(1);
    var future = executor.scheduleAtFixedRate(() -> {
        System.out.println("多线程定时器轮询");
        if (!flag.get()) {
            ScheduledFuture<?> f = futures.get(job);
            // 关闭定时器
            if (f != null) f.cancel(true);
            // 释放countDownLatch.await
            countDownLatch.countDown();
            System.out.println("标记改变,结束定时器");
        } else if (!t1.isAlive() && !t2.isAlive() && !t3.isAlive()) {
            ScheduledFuture<?> f = futures.get(job);
            // 关闭定时器
            if (f != null) f.cancel(true);
            // 释放countDownLatch.await
            countDownLatch.countDown();
            System.out.println("线程执行完成,结束定时器,查看标记状态" + flag.get());
        }
    }, 0, 100, TimeUnit.MILLISECONDS);

    futures.put(job, future);
    try {
        System.out.println("countDownLatch wait");
        countDownLatch.await();
        sw.stop();
    } catch (InterruptedException e) {
        e.printStackTrace();
        Thread.currentThread().interrupt();
    }
    // 关闭线程池,最好放在finally中
    executor.shutdown();
    log.info(String.valueOf(sw.elapsed(TimeUnit.MILLISECONDS)));

}

到此,两种计时器实现轮询方式完成。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LuciferWWP

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值