我在ThreadPoolExecutor中运行任务时发现了意外的死锁.
这个想法是一个主要任务,它启动一个改变标志的次要任务.主任务暂停,直到辅助任务更新标志.
我想知道:
corePoolSize = 2是一个安全值来防止这种死锁吗?
import java.util.concurrent.*;
class ExecutorDeadlock {
/*------ FIELDS -------------*/
boolean halted = true;
ExecutorService executor;
Runnable secondaryTask = new Runnable() {
public void run() {
System.out.println("secondaryTask started");
halted = false;
System.out.println("secondaryTask completed");
}
};
Runnable primaryTask = new Runnable() {
public void run() {
System.out.println("primaryTask started");
executor.execute(secondaryTask);
while (halted) {
try {
Thread.sleep(500);
}
catch (Throwable e) {
e.printStackTrace();
}
}
System.out.println("primaryTask completed");
}
}; …Run Code Online (Sandbox Code Playgroud)