scheduleWithFixedDelay具有并发重叠任务

时间:2013-07-22 03:23:42

标签: java concurrency executor

我正在寻找ScheduledExecutor的变体,它允许任务以特定间隔运行,而无需等待上一个任务完成。

鉴于下面的代码,有不同的输出行,间隔为5000毫秒。

假设执行间隔为50毫秒,线程池大小为10,我正在寻找一个在前550毫秒内有10条输出线的解决方案,然后暂停,直到线程被释放并可以重复使用。

    ScheduledExecutorService pollingExecutorService = Executors.newScheduledThreadPool(10);

    final Runnable pollingTask = new Runnable() {
        public void run() {
            System.out.println("running poller " + DateTime.now().toString());
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            System.out.println("5000 passed");
        }
    };

    ScheduledFuture<?> pollingHandler =
            pollingExecutorService.scheduleWithFixedDelay(pollingTask,
                    0,
                    50,
                    TimeUnit.MILLISECONDS);

    //wait secondsIdleBeforeShutdown seconds
    try {
        Thread.sleep(1000*60);
    } catch (InterruptedException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }

1 个答案:

答案 0 :(得分:0)

试试这个

    ExecutorService ex = Executors.newFixedThreadPool(10);
    for (;;) {
        List<Future<?>> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Future<?> f = ex.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("running poller " + new Date());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("5000 passed");
                }
            });
            list.add(f);
        }
        for (Future<?> f : list) {
            f.get();
        }
    }