连续运行ExecutorService任务

时间:2018-03-03 20:37:04

标签: java concurrency executorservice

我想使用方法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对象?< / p>

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

Executors.newWorkStealingPool()生成ForkJoinPool ForkJoinPool 类未实现ScheduledExecutorService接口,因此您无法将其强制转换为 ScheduledExecutorService

此外, ForkJoinPool ScheduledExecutorService 是根本不同的线程池。如果您需要使用 ScheduledExecutorService 计划每两秒执行一次任务,因为它适合您的用例。 ForkJoinPools 旨在用于您在许多线程中分配许多小工作单元的情况,而不是在您希望定期执行某些操作时。