Java线程池使用示例代码
时间: 2023-12-05 15:00:49 浏览: 87
JavaThreaddemo_DEMO_tidecme_线程池Java_
好的,以下是一个简单的Java线程池使用示例代码:
```
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
// 创建一个固定大小的线程池,大小为3
ExecutorService executor = Executors.newFixedThreadPool(3);
// 提交5个任务给线程池
for (int i = 1; i <= 5; i++) {
Task task = new Task("Task " + i);
executor.submit(task);
}
// 关闭线程池
executor.shutdown();
}
}
class Task implements Runnable {
private String name;
public Task(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("Task " + name + " is running. Thread name: " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task " + name + " is completed. Thread name: " + Thread.currentThread().getName());
}
}
```
以上代码创建了一个固定大小为3的线程池,然后提交了5个任务,每个任务打印一些信息并且暂停1秒钟。可以看到,线程池会自动分配线程来执行任务,并且线程池在执行完所有任务后自动关闭。
阅读全文