簡體   English   中英

連續運行ExecutorService任務

[英]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對象?

我認為可以通過創建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);

Executors.newWorkStealingPool()生成一個ForkJoinPool ForkJoinPool類未實現ScheduledExecutorService接口,因此無法將其強制轉換為ScheduledExecutorService

此外, ForkJoinPoolScheduledExecutorService是根本不同的線程池。 如果您需要安排一個任務使用ScheduledExecutorService每秒鍾執行一次,因為它適合您的用例。 ForkJoinPools旨在用於在許多線程中分配了許多小工作單元的情況下,而不是在您要定期執行某事時使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM