java创建公共线程池类,提供获取线程的方法
时间: 2024-02-01 07:15:25 浏览: 93
Java基础学习59.pdf
以下是一个简单的 Java 公共线程池类,提供获取线程的方法:
```java
import java.util.concurrent.*;
public class ThreadPool {
private static ThreadPool instance;
private ExecutorService executor;
private ThreadPool() {
int corePoolSize = 10;
int maxPoolSize = 100;
long keepAliveTime = 60L;
TimeUnit timeUnit = TimeUnit.SECONDS;
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
}
public static synchronized ThreadPool getInstance() {
if (instance == null) {
instance = new ThreadPool();
}
return instance;
}
public void execute(Runnable task) {
executor.execute(task);
}
public Future<?> submit(Runnable task) {
return executor.submit(task);
}
public <T> Future<T> submit(Callable<T> task) {
return executor.submit(task);
}
public void shutdown() {
executor.shutdown();
}
public boolean isShutdown() {
return executor.isShutdown();
}
public boolean isTerminated() {
return executor.isTerminated();
}
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return executor.awaitTermination(timeout, unit);
}
}
```
这个类使用了单例模式来确保只有一个线程池对象存在,可以通过 `ThreadPool.getInstance()` 方法获取该对象。线程池使用了 `ThreadPoolExecutor` 类来实现,提供了 `execute()`、`submit()` 方法来提交任务,以及 `shutdown()`、`isShutdown()`、`isTerminated()`、`awaitTermination()` 方法来控制线程池的关闭和状态查询。
阅读全文