作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的程序应该在多线程下运行很长时间。我需要能够为线程设置超时,一旦线程终止,我想再次启动它。这是我的代码:
@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);
}
最佳答案
下面的代码将一遍又一遍地对任务运行相同的代码。池将在给定时间后关闭。
这似乎符合您的要求。
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);
关于java - 如何为 Executors.newFixedThreadPool 设置超时并在超时后创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47997137/
我是一名优秀的程序员,十分优秀!