线程池
有非常的多的任务需要多线程来完成,且每个线程执行时间不会太长,这样会频繁的创建和销毁线程。频繁创建和销毁线程会比较耗性能。如果有了线程池就不要创建更多的线程来完成任务,因为线程可以重用。
线程池用维护者一个队列,队列中保存着处于等待(空闲)状态的线程。不用每次都创建新的线程。
和线程池相关的接口和类存在java.util.concurrent并发包中。
接口:
-
Executor:线程池的核心接口,负责线程的创建使用和调度的根接口。
-
ExecutorService: Executor的子接口,线程池的主要接口, 提供基本功能。
-
ScheduledExecutorService: ExecutorService的子接口,负责线程调度的子接口。
实现类:
-
ThreadPoolExecutor:ExecutorService的实现类,负责线程池的创建使用。
-
ScheduledThreadPoolExecutor:继承 ThreadPoolExecutor,并实现 ScheduledExecutorService接口,既有线程池的功能,又具有线程调度功能。
-
Executors:线程池的工具类,静态方法,负责线程池的创建。
/*创建固定大小线程池*/
newFixedThreadPool(int nThreads);
/*创建缓存线程池,线程池大小没有限制,根据需求自动调整线程数量*/
newCachedThreadPool();
/*创建单个线程的线程池,只有一个线程*/
newSingleThreadExecutor();
/*创建固定大小的线程池,可以延迟或定时执行任务*/
newScheduledThreadPool(int corePoolSize);
/*执行线程,上面构造方法创建的对象直接调用,返回值是任务类*/
Future<?> submit(Runnable task);
/*ScheduledThreadPool类下方法*/
/*创建并执行在给定延迟后启用线程,TimeUnit是时间单位,可以静态调用单位*/
schedule(Callable<V> callable, long delay, TimeUnit unit);
schedule(Runnable command, long delay, TimeUnit unit);
/*
* 整体延迟执行,按照固定速率,周期period执行,【包含线程执行时间】
* 【如果执行时间>周期,则会出现线程追赶进度的情况,在后面的timer部分会详解】
* 【与timer的scheduleAtFixedRate方法一致】
*/
scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);
/*整体延迟执行,在每一次执行终止和下一次执行开始之间都存在给定的周期延迟,【不包含线程执行时间】*/
scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit);
案例1
public class Sum {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//缓冲线线程池,没有固定线程数量,默认一个任务创建一个线程
ExecutorService executorService1 = Executors.newCachedThreadPool();
//固定5个线程,后面任务是100个,但是只能创建5个线程
ExecutorService executorService = Executors.newFixedThreadPool(5);
List<Future<Integer>> list = new ArrayList<>();
//给线程分配任务
for (int i = 0; i < 100; i++) {
//该方法返回的都是Future类
Future<Integer> future = executorService.submit(new Callable<Integer>() {
public Integer call() throws Exception {
int sum = 0;
for (int j = 0; j <= 100; j++) {
sum += j;
}
System.out.println(Thread.currentThread().getName());
return sum;
}
});
list.add(future);
}
for (Future<Integer> future