java 创建一个线程池
时间: 2023-10-14 14:24:10 浏览: 72
Java中可以使用ThreadPoolExecutor类来创建一个线程池。下面是一个简单的示例:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyThreadPool {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new MyWorkerThread("" + i);
executorService.execute(worker);
}
executorService.shutdown();
while (!executorService.isTerminated()) {
}
System.out.println("All tasks completed");
}
}
class MyWorkerThread implements Runnable {
private String message;
public MyWorkerThread(String message) {
this.message = message;
}
public void run() {
System.out.println(Thread.currentThread().getName() + " (Start) message = " + message);
processMessage();
System.out.println(Thread.currentThread().getName() + " (End)");
}
private void processMessage() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们使用Executors类中的newFixedThreadPool方法来创建一个固定大小为5的线程池。我们创建了10个任务,每个任务都是一个MyWorkerThread实例,并将它们提交给线程池执行。任务的执行是通过调用executorService.execute(worker)实现的。最后,我们调用shutdown方法来关闭线程池,并等待所有任务完成后打印"All tasks completed"。
阅读全文