java如何创建线程池
时间: 2025-02-22 09:25:13 浏览: 36
### Java 中创建线程池的方法
#### 使用 Executors 类的静态工厂方法
一种常用的方式是在Java中通过`Executors`类中的静态工厂方法来创建不同类型的线程池。这种方式简单快捷,适合于不需要高度自定义配置的情况[^2]。
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; ++i) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {}
System.out.println("Finished all threads");
}
static class WorkerThread implements Runnable {
private String command;
public WorkerThread(String s){
this.command = s;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " Start. Command = "
+ command);
processCommand();
System.out.println(Thread.currentThread().getName() + " End.");
}
protected void processCommand(){
try{
Thread.sleep(500); // Simulate work being done.
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
```
这段代码展示了如何利用 `newFixedThreadPool(int nThreads)` 方法创建固定大小的工作线程集合,并提交多个任务给它处理。当不再需要更多任务时调用 `shutdown()` 来平滑关闭线程池。
#### 自定义线程池参数化构建
对于更复杂的场景,则可以考虑直接实例化 `ThreadPoolExecutor` 并指定其七个核心参数来进行更加精细地控制[^3]:
- **corePoolSize**: 线程池维护的核心线程数。
- **maximumPoolSize**: 允许的最大线程数目。
- **keepAliveTime**: 当前活跃线程超过 corePoolSize 数量后的存活时间长度。
- **unit**: keepAliveTime 的单位。
- **workQueue**: 存储待执行的任务队列。
- **threadFactory**: 创建新线程使用的工厂对象。
- **handler**: 被用来拒绝那些无法加入到工作队列里的请求处理器。
下面是一个基于这些选项的手动创建线程池的例子:
```java
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
// 定义一个简单的拒绝策略实现
class MyRejectedPolicy implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if(!executor.isShutdown()){
throw new RuntimeException("Task is discarded at rejection policy.");
}
}
}
...
ThreadPoolExecutor executorCustomized =
new ThreadPoolExecutor(
2,
20,
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(10),
Executors.defaultThreadFactory(),
new MyRejectedPolicy()
);
for (int i = 0; i < 15; ++i) {
final int taskNumber = i;
executorCustomized.submit(() -> {
System.out.printf("Executing Task %d%n", taskNumber);
try { TimeUtil.waitSeconds((long)(Math.random()*5)); }
catch(Exception ignored){}
});
}
executorCustomized.shutdown();
while (!executorCustomized.awaitTermination(1, TimeUnit.MINUTES)){}
System.out.println("All tasks are finished!");
```
此示例说明了如何精确调整线程池的行为模式以适应特定需求,比如设置最大并发度、超时时长以及应对过载情况下的响应措施等[^4]。
阅读全文
相关推荐


















