概述
在多線程執行任務時,可以使用線程池執行任務。
相關代碼如下:
public static void main(String[] args) {
ThreadPoolExecutor executor=null;
try{
executor = new ThreadPoolExecutor(2, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(8));
// 提交任務到線程池
for (int i = 0; i < 11; i++) {
executor.execute(() -> {
try {
Thread.sleep(1000); // 模擬任務執行時間
System.out.println("任務 " + Thread.currentThread().getId() + " 執行完成...");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
catch (Exception ex){
ex.printStackTrace();
}
finally {
executor.shutdown();
}
}
這裏可以看到線程池的
1.核心線程數
2.最大線程數
3.隊列大小
我們可以測試一次最大可以提交的線程數爲
最大線程數 + 隊列大小。
如果提交的任務數大於這個數量,那麼會拋出拒絕異常。