threadpoolexecutor使用例子,JAVA
时间: 2023-03-28 16:01:19 浏览: 121
当然可以,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 = ; 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);
processMessage();
System.out.println(Thread.currentThread().getName() + " (End)");
}
private void processMessage() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
这个例子中,我们创建了一个固定大小为5的线程池,然后创建了10个WorkerThread对象,每个对象都代表一个任务,然后将这些任务提交给线程池执行。最后,我们等待所有任务执行完毕,然后关闭线程池。
阅读全文