(来自JavaGuide)
一个简单的例子
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
// 创建线程池,使用FixedThreadPool类型,固定大小为3
ExecutorService executorService = Executors.newFixedThreadPool(3);
// 提交任务给线程池
for (int i = 1; i <= 5; i++) {
int taskNumber = i;
executorService.execute(() -> {
System.out.println("Task " + taskNumber + " is being executed by " + Thread.currentThread().getName());
try {
// 模拟任务执行时间
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task " + taskNumber + " has completed");
});
}
// 关闭线程池
executorService.shutdown();
}
}
在上述代码中,我们创建了一个固定大小为3的线程池(newFixedThreadPool(3)
)。然后,我们提交了5个任务给线程池进行执行。每个任务都是一个简单的匿名函数(Lambda表达式),它打印任务编号和执行任务的线程名称,并模拟了一个任务的执行时间。
线程池会根据线程的可用性和任务的数量来调度执行。在这个例子中,由于线程池的固定大小为3,所以最多会同时执行3个任务,而剩下的2个任务会在前面的任务完成后执行
输出结果
Task 1 is being executed by pool-1-thread-1
Task 2 is being executed by pool-1-thread-2
Task 3 is being executed by pool-1-thread-3
Task 1 has completed
Task 4 is being executed by pool-1-thread-1
Task 2 has completed
Task 5 is being executed by pool-1-thread-2
Task 3 has completed
Task 4 has completed
Task 5 has completed