在專案中使用執行緒池時,使用了如下方式:
executorservice datauploadpool = executors.newfixedthreadpool(writethreadnum);
datauploadpool.execute(new thread(task))
但是這種方式下,主線程無法捕獲子執行緒中的異常,也就無法在子執行緒出現異常時採取措施。
如果換乙個實現方式就可以捕獲子執行緒異常,步驟如下:
1. 以submit方式提交執行並返回future物件
2. 執行futrue的get方法獲取執行結果
3. 捕獲get方法丟擲的執行異常
final executorservice datauploadpool = executors.newfixedthreadpool(writethreadnum);
list
results = new arraylist<>();
for (file f : file.listfiles()) }}
// 關閉執行緒池
datauploadpool.shutdown();
// 檢查執行緒池中線程是否丟擲異常,若異常則退出執行
for (future task : results) catch (exception e)
}
datadao需要實現callable介面並實現call方法:
public
abstract
class
abstractdao
implements
callable
}
多執行緒之執行執行緒異常捕獲
description 執行緒異常捕捉 author administrator create 2019 12 23 22 22 public class threadexception static void thread1 catch interruptedexception e thread....
如何主線程捕獲子執行緒的異常
第乙個 子執行緒類 public class threadexceptionrunner implements runnable 第二步 主線程類 在最後面有我自定義的兩個class是作為配置用的,有解釋 public class demothread 1 首先 實現乙個 thread.uccaug...
獲取執行緒池中任務執行數量
轉 通過執行緒池進行任務處理,有時我們需要知道執行緒池中任務的執行狀態。通過threadpoolexecutor的相關api實時獲取執行緒數量,排隊任務數量,執行完成執行緒數量等資訊。private static executorservice es new threadpoolexecutor 5...