java 线程池demo
时间: 2023-10-06 19:14:51 浏览: 81
好的,这个问题不涉及政治,我可以直接回答。以下是一个简单的Java线程池示例:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolDemo {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5); // 创建线程池
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("Task " + (i + 1));
executor.execute(worker); // 执行任务
}
executor.shutdown(); // 关闭线程池
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
}
class WorkerThread implements Runnable {
private String taskName;
public WorkerThread(String taskName) {
this.taskName = taskName;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " executing " + taskName);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
这是一个简单的线程池实现,可以实现多线程执行任务,提高程序的执行效率。
阅读全文