47.各种类型的线程池
线程池继承体系
Executor(interface)->ExecutorService(interface)->ThreadPoolExecutor(class)
Executors.newFixedThreadPool
核心线程数=最大线程数(没有救急线程被创建),所以也无需超时时间阻塞队列LinkedBlockingQueue,可以放任意数量的任务,队列容量=Integer.MAX_VALUE适用于:任务量已知,相对耗时的任务
public static void main(String[] args) {ExecutorService executorService = Executors.newFixedThreadPool(2);executorService.execute(() -> {log.debug("1");});executorService.execute(() -> {log.debug("2");});executorService.execute(() -> {log.debug("3");});}
ThreadFactory自定义线程名称
public static void main(String[] args) {ExecutorService executorService = Executors.newFixedThreadPool(2,new ThreadFactory() {private final AtomicInteger threadNumber = new AtomicInteger(1);private final String namePrefix = "xkj_";@Overridepublic Thread newThread(Runnable r) {Thread t = new Thread(r,namePrefix + threadNumber.getAndIncrement());return t;}});executorService.execute(() -> {log.debug("1");});executorService.execute(() -> {log.debug("2");});executorService.execute(() -> {log.debug("3");});}
Executors.newCachedThreadPool()
没有核心线程,全是救急线程,线程存活时间是1分钟,救急线程可以无限创建Integer.MAX_VALUE。
SynchronousQueue 同步队列,特点是,没有容量,没有线程来取是放不进去的(一手交钱,一手交货)
ExecutorService executorService = Executors.newCachedThreadPool();executorService.execute(() -> {log.debug("111");});executorService.execute(() -> {log.debug("222");});executorService.execute(() -> {log.debug("333");});
SynchronousQueue同步队列
一手交钱一手交货,没有线程来取任务,就无法添加新任务。
SynchronousQueue<Integer> synchronousQueue = new SynchronousQueue<>();new Thread(() -> {try {log.debug("putting{}", 1);synchronousQueue.put(1);//会阻塞住log.debug("putted{}", 1);log.debug("putting{}", 2);synchronousQueue.put(2);//会阻塞住log.debug("putted{}", 2);} catch (InterruptedException e) {e.printStackTrace();}}, "t1").start();new Thread(() -> {try {Integer take = synchronousQueue.take();//取出元素会让put方法后面继续执行,不再阻塞log.debug("take:{}", take);}catch (InterruptedException e) {e.printStackTrace();}}, "t2").start();
适用于:任务数比较密集,但每个任务执行时间较短的情况。
Executors.newSingleThreadExecutor
希望多个任务排队执行,线程数固定为1。
任务数多于1时,会放入无界队列排队。
任务执行完毕,这唯一的线程也不会被释放。
跟自定义创建一个单线程串行执行任务的区别:
如果任务执行失败而终止没有任何补救措施,而线程池还会新建一个线程,保证池的正常工作。
FinalizableDelegatedExecutorService应用的是装饰器模式,只是对外暴露了ExecutorService接口,因此不能调用ThreadPoolExecutor中特有的方法。
Executors.newFixedThreadPool(1)初始时为1,以后还可以修改。对外暴露的是ThreadPoolExecutor对象,可以强转后调用setCorePoolSize等方法进行修改。
ExecutorService executorService = Executors.newSingleThreadExecutor();executorService.execute(() -> {log.debug("aaa");int i = 1 / 0;});executorService.execute(() -> {log.debug("bbb");});executorService.execute(() -> {log.debug("ccc");});