[英]Run ExecutorService tasks continuously
我想使用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()
但我不知道是否有任何方法可以像ScheduledExecutorService
提供的對象那樣連續運行ExecutorService
對象?
我認為可以通過創建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);
Executors.newWorkStealingPool()
生成一個ForkJoinPool 。 ForkJoinPool類未實現ScheduledExecutorService接口,因此無法將其強制轉換為ScheduledExecutorService 。
此外, ForkJoinPool和ScheduledExecutorService是根本不同的線程池。 如果您需要安排一個任務使用ScheduledExecutorService每秒鍾執行一次,因為它適合您的用例。 ForkJoinPools旨在用於在許多線程中分配了許多小工作單元的情況下,而不是在您要定期執行某事時使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.