如何在Java中使用ScheduledThreadpoolExecutor重新启动终止的线程?
我希望有一个线程池,它被维护为固定数量的线程。我希望所有因异常或正常终止而死亡的线程都能生成它们的精确副本,以保持线程的数量 我尝试了以下代码,希望它能继续打印1-2-3-4-1-2-3-4。。。。但在循环中,它在第一次执行后停止如何在Java中使用ScheduledThreadpoolExecutor重新启动终止的线程?,java,multithreading,threadpool,Java,Multithreading,Threadpool,我希望有一个线程池,它被维护为固定数量的线程。我希望所有因异常或正常终止而死亡的线程都能生成它们的精确副本,以保持线程的数量 我尝试了以下代码,希望它能继续打印1-2-3-4-1-2-3-4。。。。但在循环中,它在第一次执行后停止 import org.junit.Test; import java.util.Optional; import java.util.concurrent.*; public class Testing { @Test public void tet
import org.junit.Test;
import java.util.Optional;
import java.util.concurrent.*;
public class Testing {
@Test
public void tet() {
ScheduledExecutorService poolExecutor =
new CustomExecutor(4);
for (int i = 1; i <= 4; i++) {
poolExecutor.execute(new Task(i));
}
}
}
class Task implements Runnable {
int x;
Task(int x) {
this.x = x;
}
@Override
public void run() {
System.out.println(x);
if (true) {
System.out.println("throwing exception " + x);
throw new RuntimeException();
}
}
}
class CustomExecutor extends ScheduledThreadPoolExecutor {
public CustomExecutor(int corePoolSize) {
super(corePoolSize);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
this.execute(r);
}
}
import org.junit.Test;
导入java.util.Optional;
导入java.util.concurrent.*;
公共类测试{
@试验
公众假期{
ScheduledExecutorService池执行器=
新客户执行人(4);
对于(int i=1;i您不需要手动重新启动死线程,当提交新任务时,执行器将检查是否需要创建新线程
在这种情况下,如果您希望任务在异常发生后继续运行,则可以捕获并处理它
此外,如果您只是执行任务,则该任务将只执行一次。如果您希望继续执行任务,并且等待任务终止,则应安排任务执行时间:
@Test
public void tet() {
ScheduledExecutorService poolExecutor =
new CustomExecutor(4);
for (int i = 1; i <= 4; i++) {
poolExecutor.scheduleAtFixedRate(new Task(i), 0, 1000, TimeUnit.MILLISECONDS);
}
try {
poolExecutor.awaitTermination(10000, TimeUnit.MILLISECONDS);
} catch (Exception e) {
}
}
@测试
公众假期{
ScheduledExecutorService池执行器=
新客户执行人(4);
对于(int i=1;我为什么不捕获它呢?这始终是一个选项。我正在测试afterExecute函数。当发生异常时,固定线程池执行器不会丢失线程,因此不清楚您想要什么。不要重新启动线程!!我编辑了问题。我尝试了您提到的方法,以固定速率调度,但输出是同样。我在这里做错了什么吗?我想让调度程序在没有异常的情况下工作。有办法吗?据我所知,没有。你必须在某个地方捕获这个执行选项。。这意味着如果线程没有抛出异常,它将不会被再次调度?这似乎很奇怪!我也尝试过不抛出错误。还是不行。为了清楚起见,编辑了这个问题。
@Test
public void tet() {
ScheduledExecutorService poolExecutor =
new CustomExecutor(4);
for (int i = 1; i <= 4; i++) {
poolExecutor.scheduleAtFixedRate(new Task(i), 0, 1000, TimeUnit.MILLISECONDS);
}
try {
poolExecutor.awaitTermination(10000, TimeUnit.MILLISECONDS);
} catch (Exception e) {
}
}