我想使用方法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
对象? 最佳答案
我认为可以通过创建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/