ThreadPoolExecutor实战
时间: 2023-10-21 20:26:44 浏览: 96
ThreadPoolExecutor是Java中的一个线程池实现类,它可以用来管理和重用线程,从而提高多线程程序的性能。下面是一个ThreadPoolExecutor的实战示例:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExecutorDemo {
public static void main(String[] args) {
// 创建一个固定大小的线程池,最多同时执行3个任务
ExecutorService executor = Executors.newFixedThreadPool(3);
// 提交任务到线程池
for (int i = 1; i <= 5; i++) {
final int taskID = i;
executor.execute(new Runnable() {
public void run() {
System.out.println("Task " + taskID + " is running.");
try {
// 模拟任务执行耗时
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task " + taskID + " is completed.");
}
});
}
// 关闭线程池
executor.shutdown();
}
}
```
在这个示例中,我们首先通过Executors类的静态方法newFixedThreadPool来创建一个固定大小的线程池,最多同时执行3个任务。然后,我们向线程池提交了5个任务,每个任务都是一个Runnable对象。这些任务会被线程池中的线程异步执行。
每个任务的run方法中,我们打印任务的ID,并模拟任务执行耗时2秒。最后,我们调用executor.shutdown()方法来关闭线程池,这将使得线程池中的线程不再接收新的任务,并在完成所有已提交任务后退出。
使用ThreadPoolExecutor可以更好地管理线程,避免不必要的线程创建和销毁开销,提高多线程程序的效率和性能。
阅读全文
相关推荐

















