Java面试题之多线程 如何创建一个Java线程池?
在Java中,创建一个线程池通常使用java.util.concurrent
包中的ExecutorService
接口及其实现类。最常用的实现类是ThreadPoolExecutor
,但通常我们会使用Executors
工厂类来简化线程池的创建。
以下是创建线程池的几种常见方式:
Executors
工厂类import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FixedThreadPoolExample {
public static void main(String[] args) {
// 创建一个固定大小的线程池
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
final int taskId = i;
executorService.submit(() -> {
System.out.println("Task " + taskId + " is running in " + Thread.currentThread().getName());
});
}
executorService.shutdown(); // 关闭线程池
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CachedThreadPoolExample {
public static void main(String[] args) {
// 创建一个可缓存的线程池
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
final int taskId = i;
executorService.submit(() -> {
System.out.println("Task " + taskId + " is running in " + Thread.currentThread().getName());
});
}
executorService.shutdown(); // 关闭线程池
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SingleThreadExecutorExample {
public static void main(String[] args) {
// 创建一个单线程的线程池
ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
final int taskId = i;
executorService.submit(() -> {
System.out.println("Task " + taskId + " is running in " + Thread.currentThread().getName());
});
}
executorService.shutdown(); // 关闭线程池
}
}
ThreadPoolExecutor
直接创建线程池如果需要更细粒度的控制,可以直接使用ThreadPoolExecutor
构造函数:
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class CustomThreadPoolExample {
public static void main(String[] args) {
// 创建一个自定义的线程池
ThreadPoolExecutor executor = new ThreadPoolExecutor(
2, // corePoolSize
4, // maximumPoolSize
60, // keepAliveTime
TimeUnit.SECONDS, // time unit for keepAliveTime
new LinkedBlockingQueue<>() // work queue
);
for (int i = 0; i < 10; i++) {
final int taskId = i;
executor.submit(() -> {
System.out.println("Task " + taskId + " is running in " + Thread.currentThread().getName());
});
}
executor.shutdown(); // 关闭线程池
}
}
Executors
类可以快速创建常用类型的线程池。ThreadPoolExecutor
可以自定义线程池的参数,如核心线程数、最大线程数、线程存活时间等。shutdown()
方法来关闭线程池,释放资源。