如何创建线程池?
2025-02-19
NEW个对象
1、通过ExecutorService
ExecutorService executor = Executors.newCachedThreadPool();
ExecutorService executor = Executors.newFixedThreadPool(nThreads);
ExecutorService executor = Executors.newSingleThreadExecutor();
ScheduledExecutorService executor = Executors.newScheduledThreadPool(corePoolSize);
2、使用 ThreadPoolExecutor 自定义线程池
ExecutorService executor = new ThreadPoolExecutor(
corePoolSize(20),
maximumPoolSize(30),
keepAliveTime(60L),
unit(TimeUnit.SECONDS),
new LinkedBlockingQueue<Runnable>()
);
3、执行任务
executor.submit(() -> {
// 任务逻辑
});
上一篇:链表反转
下一篇:java代码,随机打乱一个数组
相关文章
-
接口和抽象类的区别?
接口和抽象类都是用来定义对象的公共行为的,两者本身不能实例化,但二者有以下7点不同:
NEW个对象 2025-01-10
-
线程和进程的区别?
线程和进程的区别?
NEW个对象 2025-01-09
-
java异常分类
java异常分类
NEW个对象 2025-01-18