ScheduledExecutorService的scheduleAtFixedRate分析

ScheduledExecutorService的scheduleAtFixedRate分析java.util.concurrent.ScheduledExecutorService#scheduleAtFixedRate参考文档:https://segmentfault.com/a/1190000015190796可以看下下面的例子。@TestpublicvoidtestFixedRate(){ScheduledExecutorServicescheduledThreadPool=null;try{

大家好,欢迎来到IT知识分享网。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

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/22001.html

(0)

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信