用java 写一个线程池
时间: 2024-03-09 11:22:34 浏览: 51
以下是一个简单的 Java 线程池实现:
```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 = 1; i <= 10; i++) {
Runnable worker = new WorkerThread("Task " + i);
executor.execute(worker);
}
// 关闭线程池
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("All tasks are finished!");
}
}
class WorkerThread implements Runnable {
private String taskName;
public WorkerThread(String taskName) {
this.taskName = taskName;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is executing " + taskName);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " has finished " + taskName);
}
}
```
这个例子中,我们使用了 `ExecutorService` 接口和 `Executors` 类来创建一个具有固定线程数量的线程池。然后,我们提交了一系列任务到线程池中,每个任务都是一个实现了 `Runnable` 接口的工作线程。线程池会自动分配线程来执行这些任务,并在所有任务都执行完毕后关闭线程池。
阅读全文