线程池
线程池:提供了一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁额外开销,提高了响应的速度
线程池的工作主要是控制运行的线程的数量,处理过程中将任务放入队列,然后再线程创建后启动这些任务,如果线程数量超过了最大数量,超出数量的线程排队等候,等其他线程执行完毕,再从队列中去除任务来执行。
特点
他的主要特点为:线程复用,控制最大并发数,管理线程
- 降低资源消耗。通过重复利用以创建的线程降低线程创建和销毁造成的消耗。
- 提高响应速度。当任务到达时,任务可以不需要等到线程创建就能立即执行。
- 提高线程的可管理性。线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程可以进行统一的分配,调优和监控。
线程池的体系结构
java.util.concurrent.Executor : 负责线程的使用与调度的根接口
-
|--**ExecutorService 子接口: 线程池的主要接口
-
|--ThreadPoolExecutor 线程池的实现类
-
|--ScheduledExecutorService 子接口:负责线程的调度
-
|--ScheduledThreadPoolExecutor :继承 ThreadPoolExecutor, 实现 ScheduledExecutorService
工具类 : Executors
ExecutorService.newFixedThreadPool()
创建固定大小的线程池。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
主要特点如下:
- 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
- newFixedThreadPool创建的线程池corePoolSize和maximumPoolSize是相等的,它使用的是LinkedBlockingQueue阻塞队列.
ExecutorService newCachedThreadPool()
缓存线程池,线程池的数量不固定,可以根据需求自动的更改数量。
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
主要特点如下:
- 创建一个可缓存的线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
- newCachedThreadPool创建的线程池corePoolSize设置为0,maximumPoolSize设置为Integer.MAX_VALUE,它使用的是SynchronousQueue同步阻塞队列,也就是说来了任务就创建线程运行,当线程空闲超过60秒,就销毁线程。
ExecutorService newSingleThreadExecutor()
创建单个线程池。线程池中只有一个线程,底层代码是调用了LinkedBlockingQueue阻塞队列
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
主要特点如下
- 创建一个单线程的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序执行。
- ewFixedThreadPool创建的线程池corePoolSize和maximumPoolSize都设置为1,它使用的是LinkedBlockingQueue阻塞队列。
ScheduledExecutorService newScheduledThreadPool()
创建固定大小的线程,可以延迟或定时的执行任务。 DelayedWorkQueue是ScheduledThreadPoolExecutor中的一个静态类,功能类似DelayQueue(使用优先级队列实现的延迟无界阻塞队列)
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
示例代码
public class ThreadPoolExcutorDemo {
public static void main(String[] args) {
//ExecutorService threadPool = Executors.newFixedThreadPool(5); //一池5个处理线程
//ExecutorService threadPool = Executors.newSingleThreadExecutor(); //一池一处理线程
ExecutorService threadPool = Executors.newCachedThreadPool(); //一池N处理线程
try{
for (int i = 0; i < 10; i++) {
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName());
});
TimeUnit.MILLISECONDS.sleep(1);
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
}