在Java中,要控制新建線程的并發數量,可以使用線程池(ExecutorService)來實現。線程池允許你限制同時運行的線程數量,從而有效地管理系統資源。以下是一個簡單的示例,展示了如何使用ExecutorService來限制線程并發數量:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPoolExample {
public static void main(String[] args) {
// 創建一個固定大小的線程池,最多同時運行3個線程
ExecutorService executorService = Executors.newFixedThreadPool(3);
// 提交任務到線程池
for (int i = 0; i < 10; i++) {
executorService.submit(() -> {
System.out.println("Task executed by thread: " + Thread.currentThread().getName());
try {
// 模擬任務執行耗時
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
// 關閉線程池,不再接受新的任務
executorService.shutdown();
try {
// 等待所有任務完成
if (!executorService.awaitTermination(30, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
}
}
}
在這個示例中,我們創建了一個固定大小為3的線程池,然后提交了10個任務到線程池。線程池會自動分配任務給空閑的線程,并確保同時運行的線程數量不超過3個。當所有任務完成后,我們關閉線程池。