jav threadpoolexecutor使用例子
时间: 2023-07-11 09:26:26 浏览: 122
好的,下面是一个使用 Java ThreadPoolExecutor 的例子:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class ThreadPoolExample {
public static void main(String[] args) {
// 创建线程池
ExecutorService executor = Executors.newFixedThreadPool(5);
// 执行任务
for (int i = 1; i <= 10; i++) {
Runnable worker = new WorkerThread("Task " + i);
executor.execute(worker);
}
// 关闭线程池
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all tasks");
}
}
class WorkerThread implements Runnable {
private String task;
public WorkerThread(String task) {
this.task = task;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " Start. Task = " + task);
processTask();
System.out.println(Thread.currentThread().getName() + " End.");
}
private void processTask() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return this.task;
}
}
```
这个例子创建了一个固定大小的线程池,并执行了10个任务。每个任务是一个 WorkerThread 对象,它会打印一些信息并执行一些处理。在全部任务执行完成之后,线程池被关闭。
阅读全文