如何为Executors.newFixedThreadPool设置超时并在达到超时后创建线程

问题描述 投票:0回答:1

我的程序应该运行多线程很长一段时间。我需要能够为线程设置超时,一旦线程终止,我想再次启动它。这是我的代码:

    @Test
    public void testB() throws InterruptedException {
        final ExecutorService threadPool = Executors.newFixedThreadPool(2);
        for(int i=0; i<2; i++){
            threadPool.submit(new Runnable() {
                public void run() {
                        System.out.println("thread start: " + Thread.currentThread().getName());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            });
        }
        threadPool.shutdown();
        threadPool.awaitTermination(100000, TimeUnit.SECONDS);
    }
java multithreading
1个回答
1
投票

下面的代码会一遍又一遍地对任务执行相同的操作。在给定的时间后,池将被关闭。

这似乎做你要求的。

final ExecutorService threadPool = Executors.newFixedThreadPool(2);

for(int i = 0; i < 2; i++){
    final int taskNb = i;
    threadPool.submit(new Runnable() {
        public void run() {
            System.out.println("Thread " + taskNb + " start: " + Thread.currentThread().getName());
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // Submit same task again
            threadPool.submit(this);

        }
    });
}

// Only shutdown the pool after given amount of time
Thread.sleep(100_000_000);
threadPool.shutdown();

// Wait for running tasks to finish
threadPool.awaitTermination(5, TimeUnit.SECONDS);
© www.soinside.com 2019 - 2024. All rights reserved.