ScheduledExecutorService的scheduleAtFixedRate分析

java.util.concurrent.ScheduledExecutorService#scheduleAtFixedRate

参考文档:

https://segmentfault.com/a/1190000015190796

可以看下下面的例子。

    @Test
    public void testFixedRate(){

        ScheduledExecutorService scheduledThreadPool = null;
        try {
            scheduledThreadPool = Executors.newScheduledThreadPool(4);
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            System.out.println("submit a callable task to threadpool, current time:" + sdf.format(new Date()));
            ScheduledFuture<?> scheduledFuture = scheduledThreadPool.scheduleAtFixedRate(() -> {
                System.out.println(Thread.currentThread().getName() + " | start to execute task, current time :" + sdf.format(new Date()));
                try {
                    Random random = new Random();
                    int i = random.nextInt(7);
                    System.out.println("current i="+i);
                    TimeUnit.SECONDS.sleep(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, 2L, 3L, TimeUnit.SECONDS);

            TimeUnit.SECONDS.sleep(200L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (scheduledThreadPool != null) {
                System.out.println("close the schedule threadpool!");
                scheduledThreadPool.shutdown();
            }
        }
    }

如下是执行的结果

submit a callable task to threadpool, current time:20:03:07
pool-1-thread-1 | start to execute task, current time :20:03:09
current i=4
pool-1-thread-1 | start to execute task, current time :20:03:13
current i=5
pool-1-thread-2 | start to execute task, current time :20:03:18
current i=1
pool-1-thread-1 | start to execute task, current time :20:03:19
current i=4
pool-1-thread-1 | start to execute task, current time :20:03:23
current i=4
pool-1-thread-1 | start to execute task, current time :20:03:27
current i=2
pool-1-thread-1 | start to execute task, current time :20:03:29
current i=1
pool-1-thread-1 | start to execute task, current time :20:03:30
current i=3
pool-1-thread-1 | start to execute task, current time :20:03:33
current i=3
pool-1-thread-4 | start to execute task, current time :20:03:36
current i=0
pool-1-thread-4 | start to execute task, current time :20:03:39
current i=6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值