我在ThreadPoolExecutor中運行任務時發現了一個意外的死鎖。Executor中的意外死鎖
這個想法是啓動改變標誌的輔助任務的主要任務。 主任務暫停,直到輔助任務更新標誌。
- 如果corePoolSize> = 2,則主任務按預期完成。
- 如果corePoolSize < 2似乎是次要任務是enquenqued但從未啓動。
- 改爲使用SynchronousQueue,即使對於corePoolSize = 0,主任務也會完成。
我想知道:
- 什麼是死鎖的原因?從 文檔看來似乎不明顯。
- 爲什麼使用SynchronousQueue代替LinkedBlockingQueue可防止死鎖?
是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"); } }; /*-------- EXECUTE -----------*/ void execute(){ executor.execute(primaryTask); } /*-------- CTOR -----------*/ ExecutorDeadlock(int corePoolSize,BlockingQueue<Runnable> workQueue) { this.executor = new ThreadPoolExecutor(corePoolSize, 4,0L, TimeUnit.MILLISECONDS, workQueue); } /*-------- TEST -----------*/ public static void main(String[] args) { new ExecutorDeadlock(2,new LinkedBlockingQueue<>()).execute(); //new ExecutorDeadlock(1,new LinkedBlockingQueue<>()).execute(); //new ExecutorDeadlock(0,new SynchronousQueue<>()).execute(); } }
你的意思是corePoolSize包括任務來管理隊列? – plastilino
它指定執行程序線程數 – Antoniossss
對不起,我無法得到它。最多允許4個線程共存。並且還有SyncQueue情況... – plastilino