1

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

给定下面的代码,每隔 5000 毫秒就有 12 行不同的输出。

给定 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.
    }
4

1 回答 1

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();
        }
    }
于 2013-07-22T03:53:22.780 回答