简体   繁体   中英

Java8 ScheduledExecutorService.scheduleAtFixedRate()

I'm reading a java8 book and come across the difference between scheduleAtFixedRate and scheduleWithFixedDelay methods from ScheduledExecutorService .

I understand the difference between these two methods on the book, however when I tried to write a simple code. It's not so clear why scheduleAtFixedRate behaves synchronously .

As you can see, I'm allocating 100 threads in the pool. And the scheduler will submit a new task every 1ms, and per task, there's a delay of 1s.

    ScheduledExecutorService s = Executors.newScheduledThreadPool(100);
    s.scheduleAtFixedRate(() -> {
        int num = new Random().nextInt(100);
        System.out.println("Hello World" + num);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Finished" + num);
    }, 0, 1, TimeUnit.MILLISECONDS);

But why am I getting this output ? A new task will run only after the other.

Hello World94
Finished94
Hello World14
Finished14
Hello World90
Finished90
Hello World26
Finished26

Take a look at the javadoc for ScheduledThreadPoolExecutor#scheduleAtFixedRate

If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.

So do not await for it to execute concurrently, it will always execute sequentially..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM