实现一个线程池工具类,里面有自己定义的核心线程数和最大线程数
时间: 2023-07-01 07:18:29 浏览: 102
下面是一个简单的线程池工具类的示例代码,其中包含了核心线程数和最大线程数的定义:
```
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class MyThreadPool {
private static final int CORE_POOL_SIZE = 5;
private static final int MAX_POOL_SIZE = 10;
private static final int QUEUE_CAPACITY = 100;
private static final long KEEP_ALIVE_TIME = 1L;
private static ThreadPoolExecutor threadPoolExecutor;
static {
BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(QUEUE_CAPACITY);
threadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAX_POOL_SIZE,
KEEP_ALIVE_TIME,
TimeUnit.SECONDS,
queue
);
}
public static void execute(Runnable task) {
threadPoolExecutor.execute(task);
}
public static void shutdown() {
threadPoolExecutor.shutdown();
}
}
```
在这个示例代码中,我们定义了一个静态的线程池Executor对象,通过静态代码块初始化,其中包含了核心线程数、最大线程数、任务队列容量等参数。提供了execute方法用于向线程池中提交任务,同时还提供了shutdown方法用于关闭线程池。你可以根据业务需求修改这些参数。
阅读全文