实现多线程的方式有很多种,今天我们就来说下目前最好用的多线程的实现方式,使用ExecutorService。为什么说它好用,是因为new Thread的弊端有很多。下面有张表格可以对比下:
new Thread的弊端 | ExecutorService |
a:每次new Thread新建对象性能差; | a:可以重用存在的线程,减少对象创建、消亡的开销,性能佳 |
b:线程缺乏统一管理,如果一直新建线程,线程之间相互竞争; | b:可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞。 |
c:缺乏更多的功能,例如定时执行; | c. 提供定时执行、定期执行、单线程、并发数控制等功能。 |
so,我们要用ExecutorService。
接下来我们从两方面学习ExecutorService:一 代码, 二线程池。
一:代码
分两种情况,一种是没有返回值的,另一种是有返回值的。
a:没有返回值的,需要调用Runnable
1.源码的接口如下
2.demo
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
执行结果:pool-1-thread-1
b:有返回值的,调用Callable
1.源码的接口如下
2.demo:
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
Future future = fixedThreadPool.submit(new Callable<String>() {
public String call(){ return "执行";}
});
try {
String result = (String)future.get();
System.out.println(result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
结果:执行
二:线程池
上面的demo中,我们使用了ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);其实,newFixedThreadPool只是其中一种创建线程池的方式,线程池的类型有很多种,下面我们会有介绍。不过,介绍之前,我想先说说ThreadPoolExecutor。源码如下
所有的线程池最终都是通过这个方法来创建的。
corePoolSize : 核心线程数,一旦创建将不会再释放。如果创建的线程数还没有达到指定的核心线程数量,将会继续创建新的核心线程,直到达到最大核心线程数后,核心线程数将不在增加;如果没有空闲的核心线程,同时又未达到最大线程数,则将继续创建非核心线程;如果核心线程数等于最大线程数,则当核心线程都处于激活状态时,任务将被挂起,等待空闲线程来执行。
maximumPoolSize : 最大线程数,允许创建的最大线程数量。如果最大线程数等于核心线程数,则无法创建非核心线程;如果非核心线程处于空闲时,超过设置的空闲时间,则将被回收,释放占用的资源。
keepAliveTime : 也就是当线程空闲时,所允许保存的最大时间,超过这个时间,线程将被释放销毁,但只针对于非核心线程。
unit : 时间单位,TimeUnit.SECONDS等。
workQueue : 任务队列,存储暂时无法执行的任务,等待空闲线程来执行任务。
线程池的其它创建类型:
源代码 | ||
ExecutorService cachePool = Executors.newCachedThreadPool(); | public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>()); } | 创建的都是非核心线程,而且最大线程数为Interge的最大值,空闲线程存活时间是1分钟。如果有大量耗时的任务,则不适该创建方式。它只适用于生命周期短的任务。 |
ExecutorService singlePool = Executors.newSingleThreadExecutor(); | public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); } | 只用一个线程来执行任务,保证任务按FIFO顺序一个个执行。 |
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); | public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } | 创建固定数量的可复用的线程数,来执行任务。当线程数达到最大核心线程数,则加入队列等待有空闲线程时再执行。 |
ExecutorService scheduledPool = Executors.newScheduledThreadPool(5); | public static ScheduledExecutorService newSingleThreadScheduledExecutor() { return new DelegatedScheduledExecutorService (new ScheduledThreadPoolExecutor(1)); } | 创建一个定长线程池,支持定时及周期性任务执行。 |