首先使用 ExecutorService 接口及其实现类 ThreadPoolExecutor 来创建自定义线程池。 先 创建一个自定义线程池的工厂类,这个类继承自 ThreadFactory 接口,用于创建线程: import java.util.concurren
首先使用ExecutorService
接口及其实现类ThreadPoolExecutor
来创建自定义线程池。
先创建一个自定义线程池的工厂类,这个类继承自ThreadFactory
接口,用于创建线程:
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
public class CustomThreadFactory implements ThreadFactory {
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String threadNamePrefix;
public CustomThreadFactory(String threadNamePrefix) {
this.threadNamePrefix = threadNamePrefix;
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, threadNamePrefix + threadNumber.getAndIncrement());
t.setDaemon(false); // 设置为非守护线程
return t;
}
}
接下来,创建一个自定义线程池的类,这个类初始化ThreadPoolExecutor
:
import java.util.concurrent.*;
public class CustomThreadPool {
private static final int CORE_POOL_SIZE = 5;
private static final int MAX_POOL_SIZE = 10;
private static final long KEEP_ALIVE_TIME = 60L;
private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
private final ExecutorService executorService;
public CustomThreadPool() {
ThreadFactory threadFactory = new CustomThreadFactory("CustomThread-");
executorService = new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAX_POOL_SIZE,
KEEP_ALIVE_TIME,
TIME_UNIT,
new LinkedBlockingQueue<>(),
threadFactory
);
}
public void submitTask(Runnable task) {
executorService.submit(task);
}
public void shutdown() {
executorService.shutdown();
}
}
你可以在项目中使用这个自定义线程池。以下是一个简单的例子:
public class ExampleUsage {
public static void main(String[] args) {
// 创建自定义线程池
CustomThreadPool customThreadPool = new CustomThreadPool();
// 提交任务到线程池
for (int i = 0; i < 10; i++) {
int taskNumber = i;
customThreadPool.submitTask(() -> {
System.out.println("Task " + taskNumber + " executed by thread: " + Thread.currentThread().getName());
});
}
// 关闭线程池
customThreadPool.shutdown();
}
}
在这个例子中,ExampleUsage
类创建了一个CustomThreadPool
对象,并提交了10个简单的任务到线程池。每个任务输出了当前线程的名称。最后,调用shutdown
方法关闭线程池。
当然具体的细节要根据项目中的实际使用去选择合适的配置等信息,来满足其需求。
【感谢龙石为本站提供api网关 http://www.longshidata.com/pages/apigateway.html】