连续运行ExecutorService任务

问题描述 投票:0回答:2

我想使用方法newWorkStealingPool()获取线程并每1 sec连续运行它们。使用以下示例代码:

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

        Runnable task = () -> System.out.println("Scheduling: " + System.currentTimeMillis());

        int initialDelay = 0;
        int period = 1;
        executor.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);

我可以连续运行任务,但我想使用方法newWorkStealingPool()来获取线程。使用以下代码:

ScheduledExecutorService executor = (ScheduledExecutorService)Executors.newWorkStealingPool();

        Runnable task = () -> System.out.println("Scheduling: " + System.currentTimeMillis());

        int initialDelay = 0;
        int period = 1;
        executor.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);

我收到了错误:

java.util.concurrent.ForkJoinPool cannot be cast to java.util.concurrent.ScheduledExecutorService

使用ExecutorService对象可以使用newWorkStealingPool(),但我不知道是否有任何方法像ExecutorService提供的对象一样连续运行ScheduledExecutorService对象?

java concurrency executorservice
2个回答
2
投票

我认为这可以通过创建ScheduledExecutorServiceForkJoinPool来实现。 ScheduledExecutorService将用于按指定的时间间隔向ForkJoinPool提交任务。而ForkJoinPool将执行这些任务。

    ForkJoinPool executor = (ForkJoinPool) Executors.newWorkStealingPool();
    // this will be only used for submitting tasks, so one thread is enough
    ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
    Runnable task = () -> System.out.println("Scheduling: " + System.currentTimeMillis());
    int initialDelay = 0;
    int period = 1;
    scheduledExecutor.scheduleAtFixedRate(()->executor.submit(task), initialDelay, period, TimeUnit.SECONDS);

0
投票

Executors.newWorkStealingPool()产生一个ForkJoinPool。 ForkJoinPool类没有实现ScheduledExecutorService接口,因此您无法将其强制转换为ScheduledExecutorService。

此外,ForkJoinPool和ScheduledExecutorService是根本不同的线程池。如果您需要使用ScheduledExecutorService计划每秒执行一次任务,因为它适合您的用例。 ForkJoinPools适用于你有许多小工作单元分为多个线程的情况,而不适用于你想要经常执行某些程序的情况。

© www.soinside.com 2019 - 2024. All rights reserved.