java - 连续运行ExecutorService任务

标签 java concurrency executorservice

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

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 提供什么对象?

最佳答案

我认为这可以通过创建 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);

关于java - 连续运行ExecutorService任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49088973/

相关文章:

java - 同步属性读取为非同步属性

java - 无法让 servlet 打印到文本文件

ios - 为什么 Core Data 并发调试工具会导致我的 iOS 应用程序崩溃?

go - 如何计算Go并发函数的执行时间

java - 为什么当执行器的线程出现异常时,它并没有耗尽可用线程?

java - 对 Future.get() block 的方法调用。这真的很可取吗?

java - 我需要处理 executorservice 中的异常吗

java - 字符串索引超出范围 : 1

java - 如何分割字符串并保存分割的 2 个字符?

c# - .NET 的并发收集超时?