标签:eth 执行 cached locking com thread pool queue time
避免使用 Executors 来创建线程。
说明:
Executors各个方法的弊端:
1)newFixedThreadPool和newSingleThreadExecutor: 主要问题是堆积的请求处理队列可能会耗费非常大的内存,甚至OOM。
2)newCachedThreadPool和newScheduledThreadPool: 主要问题是线程数最大数是Integer.MAX_VALUE,可能会创建数量非常多的线程,甚至OOM。
正例1:
// 定时执行线程池
//org.apache.commons.lang3.concurrent.BasicThreadFactory
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
正例2:
//通用线程池
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder() .setNameFormat("demo-pool-%d").build();
ExecutorService pool = new ThreadPoolExecutor(5, 200, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue (1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
pool.execute(()-> System.out.println(Thread.currentThread().getName()));
pool.shutdown(); //gracefully shutdown
正例3:
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
// 请引入一个已经设置过工厂名称的线程工厂对象
//in code userThreadPool.execute(thread);
[多线程] 线程池的使用
标签:eth 执行 cached locking com thread pool queue time
原文地址:https://www.cnblogs.com/guihong/p/13095942.html