Java创建线程池的步骤
时间: 2023-05-14 17:06:36 浏览: 114
线程池.zip,互斥锁+条件变量+队列,实现线程池,包括线程池的创建,塞任务,和销毁线程池
在Java中创建线程池的步骤如下:
1. 通过使用java.util.concurrent.Executors类的静态工厂方法创建ExecutorService实例。
2. 为ExecutorService指定线程池大小。
3. 创建并执行任务。
4. 调用shutdown()方法关闭ExecutorService。
示例代码:
```
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");
}
}
```
阅读全文