使用java语言创建线程池源代码
时间: 2023-11-29 13:05:29 浏览: 37
以下是使用 Java 语言创建线程池源代码的示例:
```
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
// 创建一个可重用固定线程数的线程池
ExecutorService threadPool = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
// 执行Runnable
threadPool.execute(worker);
}
// 立即关闭线程池
threadPool.shutdown();
// 等待所有任务执行完成
while (!threadPool.isTerminated()) {
}
System.out.println("所有线程均已执行完成");
}
}
class WorkerThread implements Runnable {
private String message;
public WorkerThread(String message) {
this.message = message;
}
public void run() {
System.out.println(Thread.currentThread().getName() + " 开始执行: " + message);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 结束执行: " + message);
}
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)