用java声明一段线程池
时间: 2023-11-14 12:16:17 浏览: 51
以下是使用Java声明线程池的示例代码:
```
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
int numOfThreads = 5;
ExecutorService executorService = Executors.newFixedThreadPool(numOfThreads);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("Task " + i);
executorService.execute(worker);
}
executorService.shutdown();
while (!executorService.isTerminated()) {
}
System.out.println("All tasks completed successfully!");
}
}
class WorkerThread implements Runnable {
private String task;
public WorkerThread(String task) {
this.task = task;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " executing " + task);
// Perform some task here...
}
}
```
此示例中使用 `ExecutorService` 和 `Executors.newFixedThreadPool()` 方法创建了一个固定大小的线程池,其中包含 5 个线程。然后,我们将 10 个任务分配给线程池。线程池将按顺序处理这些任务,并在完成所有任务后关闭。每个任务都由一个 `WorkerThread` 实例表示,该实例实现了 `Runnable` 接口,并在 `run()` 方法中执行实际的工作。当线程池中所有任务都已完成时,将输出一条消息。
阅读全文