帮忙么网 > JAVA > 当前页面

如何创建线程池?

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(() -> {
    // 任务逻辑
});

相关文章

  • 链表反转

    链表反转

    NEW个对象 2025-02-12

  • 什么是反射机制?为什么慢?

    反射机制是指在运行时能获取到自身信息,只要给出类名,就可以访问类的属性和方法。

    NEW个对象 2025-01-09

  • 有哪些数据安全的方案?

    1、锁 2、单线程,比如:redis 3、不共享变量,比如:ThreadLocal 4、原子操作,比如:AtomicInteger 5、不可变模式,比如:一旦创建不能修改,修改就会再次创建一个新的对象,String 6、读写分离,写时复制,比如:CopyOnWriteArrayList

    NEW个对象 2025-02-11

推荐文章