创建一个线程池,启动5个线程执行10次计数任务Java
时间: 2023-02-08 08:19:48 浏览: 293
在 Java 中创建线程池可以使用 Executor 框架,其中 Executors 类提供了一系列静态工厂方法来创建线程池。
示例代码如下:
```
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 CountTask();
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
}
class CountTask implements Runnable {
@Override
public void run() {
// Perform the counting task here
System.out.println("Thread " + Thread.currentThread().getName() + " is performing the task");
}
}
```
其中 `newFixedThreadPool(5)` 创建了一个固定大小为 5 的线程池,然后在循环中提交了10个任务,线程池会自动分配线程来执行这些任务。