线程使用上的常见问题
- new Thread().start()
- 线程的繁忙创建和销毁
- 线程的数据过多,会导致CPU资源的上下文切换开销问题
java中提供的四种常见的线程池
- newFixedThreadPool :固定线程数量
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
- newSingleThreadExecutor :只有一个线程的线程池
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory));
}
- newCachedThreadPool :可缓存的线程池 -> 理论上说有多少个请求就可以创建多少个线程来处理
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}
- newScheduledThreadPool :提供指定周期执行的线程池
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
实现线程复用原理拆解
- 实现线程重复使用的唯一方法就是让线程一直运行中
- 线程一直运行中如何获取新的任务呢,【可以使用共享队列AQS,让所有线程从里面获取任务】
- 考虑到如果没有任务的时候让线程停止,避免浪费cpu。有任务唤醒,没有任务着阻塞,类似一个生产者和消费者关系【可以使用LinkedBlockingQueue,获取任务】
- 拒绝策略:在队列已满的情况下如何处理
ExecutorService.execute() 底层原理
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get(); // 获取当前线程池创建线程
if (workerCountOf(c) < corePoolSize