java的threadpoolexecutor使用例子
时间: 2023-10-17 22:23:12 浏览: 81
ThreadpoolExecutor是Java中的一个线程池管理工具,它可以让我们更好地控制线程的数量和执行情况,以下是一个简单的ThreadpoolExecutor使用例子:
```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");
}
}
class WorkerThread implements Runnable {
private String message;
public WorkerThread(String s) {
this.message = s;
}
public void run() {
System.out.println(Thread.currentThread().getName() + " (Start) message = " + message);
processCommand();
System.out.println(Thread.currentThread().getName() + " (End)");
}
private void processCommand() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public String toString() {
return this.message;
}
}
```
这个例子定义了一个ExecutorService对象executor,它是由Static方法Executors.newFixedThreadPool(5)初始化而来,5代表着线程池中线程的数量固定为5。创建了一个WorkerThread对象,将其添加到executor中,然后调用executor.shutdown()方法,用于关闭线程池,所有任务都已完成执行。
阅读全文