在Java中,实现一个单例模式的线程池,可以使用ExecutorService接口,下面是具体代码:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
// 获取线程池实例
ExecutorService threadPool = SingletonThreadPool.getInstance();
// 在这里使用线程池执行任务
for (int i = 0; i < 10; i++) {
final int taskNumber = i;
// threadPool.execute(()->{
// System.out.println("Task " + taskNumber + " is running on thread " + Thread.currentThread().getName());
// });
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println("Task " + taskNumber + " is running on thread " + Thread.currentThread().getName());
}
});
}
// 关闭线程池
threadPool.shutdown();
}
}
class SingletonThreadPool{
private static ExecutorService instance;
private SingletonThreadPool(){
// 私有构造方法,防止外部直接实例化
}
public static synchronized ExecutorService getInstance(){
if(instance == null){
instance = Executors.newFixedThreadPool(5);
}
return instance;
}
}
在这个例子中,SingletonThreadPool类采用了懒汉式的单例模式,确保只有在需要时才创建线程池。通过getInstance方法获取线程池实例,并使用execute方法提交任务。最后,在程序结束时,调用shutdown方法关闭线程池。
但需要注意的是,这只是一个简单的示例。在实际应用中,可能还需要根据具体的需求调整线程池的配置参数,比如线程池的大小、任务队列的类型等。同时也建议自己构造线程池,不使用现有的4种线程池类型,避免请求(任务)的堆积或大量线程的创建,从而避免OOM。