我想使用方法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
提供什么对象?
最佳答案
我认为这可以通过创建 ScheduledExecutorService
和 ForkJoinPool
来实现。 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/