Java并发编程:Java的四种线程池的使用,以及自定义线程工厂

目录

引言

四种线程池

newCachedThreadPool:可缓存的线程池

newFixedThreadPool:定长线程池

newSingleThreadExecutor:单线程线程池

newScheduledThreadPool:支持定时的定长线程池

自定义ThreadFactory

引言

通过前面的文章,我们学习了Executor框架中的核心类ThreadPoolExecutor ,对于线程池的核心调度机制有了一定的了解,并且成功使用ThreadPoolExecutor 创建了线程池。

而在Java中,除了ThreadPoolExecutor ,Executor框架中还提供了四种线程池,这四种线程池都是直接或间接配置ThreadPoolExecutor的参数实现的,对于ThreadPoolExecutor类不熟悉的读者可以参考Java并发编程:Java线程池核心ThreadPoolExecutor的使用和原理分析

四种线程池

四种线程池分别是:newCachedThreadPool、newFixedThreadPool 、newScheduledThreadPool 和newSingleThreadExecutor ,下面对这几个线程池一一讲解。

newCachedThreadPool:可缓存的线程池

源码:

publicstaticExecutorServicenewCachedThreadPool(){returnnewThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,newSynchronousQueue());}

newCachedThreadPool的方法中是返回一个ThreadPoolExecutor实例,从源码中可以看出该线程池的特点:

1、该线程池的核心线程数量是0,线程的数量最高可以达到Integer 类型最大值;

2、创建ThreadPoolExecutor实例时传过去的参数是一个SynchronousQueue实例,说明在创建任务时,若存在空闲线程就复用它,没有的话再新建线程。

3、线程处于闲置状态超过60s的话,就会被销毁。

用法:

publicstaticvoidmain(String[] args){//定义ExecutorService实例ExecutorService cachedThreadPool = Executors.newCachedThreadPool();for(inti =0; i <10; i++) {finalintindex = i;try{ Thread.sleep(index *1000); }catch(InterruptedException e) { e.printStackTrace(); }//调用execute方法cachedThreadPool.execute(newRunnable() {@Overridepublicvoidrun(){ System.out.println(Thread.currentThread() +":"+ index); } }); }}

上面的代码因为每次循环都是隔一秒执行,这个时间足够之前的线程工作完毕,并在新循环中复用这个线程,程序的运行结果如下:

Thread[pool-1-thread-1,5,main]:0Thread[pool-1-thread-1,5,main]:1Thread[pool-1-thread-1,5,main]:2Thread[pool-1-thread-1,5,main]:3Thread[pool-1-thread-1,5,main]:4Thread[pool-1-thread-1,5,main]:5Thread[pool-1-thread-1,5,main]:6Thread[pool-1-thread-1,5,main]:7Thread[pool-1-thread-1,5,main]:8Thread[pool-1-thread-1,5,main]:9

newFixedThreadPool:定长线程池

源码:

publicstaticExecutorServicenewFixedThreadPool(intnThreads){returnnewThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,newLinkedBlockingQueue());}

线程池特点:

1、线程池的最大线程数等于核心线程数,并且线程池的线程不会因为闲置超时被销毁。

2、使用的列队是LinkedBlockingQueue,表示如果当前线程数小于核心线程数,那么即使有空闲线程也不会复用线程去执行任务,而是创建新的线程去执行任务。如果当前执行任务数量大于核心线程数,此时再提交任务就在队列中等待,直到有可用线程。

用法:

publicstaticvoidmain(String[] args){ ExecutorService cachedThreadPool = Executors.newFixedThreadPool(3);for(inti =0; i <10; i++) {finalintindex = i;try{ Thread.sleep(index *1000); }catch(InterruptedException e) { e.printStackTrace(); } cachedThreadPool.execute(newRunnable() {@Overridepublicvoidrun(){ System.out.println(Thread.currentThread() +":"+ index); } }); }}

定义一个线程数为3的线程池,循环10次执行,可以发现运行的线程永远只有三个,结果如下:

Thread[pool-1-thread-1,5,main]:0Thread[pool-1-thread-2,5,main]:1Thread[pool-1-thread-3,5,main]:2Thread[pool-1-thread-1,5,main]:3Thread[pool-1-thread-2,5,main]:4Thread[pool-1-thread-3,5,main]:5Thread[pool-1-thread-1,5,main]:6Thread[pool-1-thread-2,5,main]:7Thread[pool-1-thread-3,5,main]:8Thread[pool-1-thread-1,5,main]:9

newSingleThreadExecutor:单线程线程池

源码:

publicstaticExecutorServicenewSingleThreadExecutor(){returnnewFinalizableDelegatedExecutorService (newThreadPoolExecutor(1,1,0L, TimeUnit.MILLISECONDS,newLinkedBlockingQueue()));}

从源码就可以看出,该线程池基本就是只有一个线程数的newFixedThreadPool,它只有一个线程在工作,所有任务按照指定顺序执行。

用法:

和newFixedThreadPool类似,只是一直只有一个线程在工作,这里就不贴代码了。

newScheduledThreadPool:支持定时的定长线程池

源码:

publicstaticScheduledExecutorServicenewScheduledThreadPool(intcorePoolSize){returnnewScheduledThreadPoolExecutor(corePoolSize);}publicScheduledThreadPoolExecutor(intcorePoolSize){super(corePoolSize, Integer.MAX_VALUE,0, NANOSECONDS,newDelayedWorkQueue());}publicThreadPoolExecutor(intcorePoolSize,intmaximumPoolSize,longkeepAliveTime, TimeUnit unit, BlockingQueue workQueue){this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); }

newScheduledThreadPool的方法不是直接返回一个ThreadPoolExecutor实例,而是通过有定时功能的ThreadPoolExecutor,也就是ScheduledThreadPoolExecutor 来返回ThreadPoolExecutor实例,从源码中可以看出:

1、该线程池可以设置核心线程数量,最大线程数与newCachedThreadPool一样,都是Integer.MAX_VALUE。

2、该线程池采用的队列是DelayedWorkQueue,具有延迟和定时的作用。

用法:

publicstaticvoidmain(String[] args) { ExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);//延迟3秒执行,只执行一次((ScheduledExecutorService) scheduledThreadPool).schedule(newRunnable() { @Overridepublicvoidrun() { System.out.println("延迟========"); } },3,TimeUnit.SECONDS);//延迟1秒后每隔两秒执行一次((ScheduledExecutorService) scheduledThreadPool).scheduleAtFixedRate(newRunnable() { @Overridepublicvoidrun() { System.out.println("执行============"); } },1,2,TimeUnit.SECONDS);//单位是秒}

自定义ThreadFactory

四种线程池的使用就说到这里了,值得说明的是,除了上面的参数外,Executors类中还给这四种线程池提供了可传ThreadFactory的重载方法,以下是它们的源码:

publicstaticExecutorServicenewSingleThreadExecutor(ThreadFactory threadFactory){returnnewFinalizableDelegatedExecutorService (newThreadPoolExecutor(1,1,0L, TimeUnit.MILLISECONDS,newLinkedBlockingQueue(), threadFactory));}publicstaticExecutorServicenewCachedThreadPool(ThreadFactory threadFactory){returnnewThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,newSynchronousQueue(), threadFactory);}publicstaticScheduledExecutorServicenewScheduledThreadPool(intcorePoolSize, ThreadFactory threadFactory){returnnewScheduledThreadPoolExecutor(corePoolSize, threadFactory);}publicstaticExecutorServicenewFixedThreadPool(intnThreads, ThreadFactory threadFactory){returnnewThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,newLinkedBlockingQueue(), threadFactory);}

ThreadFactory是一个接口类,也就是我们经常说的线程工厂,只有一个方法,可以用于创建线程:

Thread newThread(Runnabler);

默认情况下,ThreadPoolExecutor构造器传入的ThreadFactory 参数是Executors类中的defaultThreadFactory(),相当于一个线程工厂,帮我们创建了线程池中所需的线程。

除此之外,我们也可以自定义ThreadFactory,并根据自己的需要来操作线程,下面是实例代码:

publicstaticvoidmain(String[] args) { ExecutorService service =newThreadPoolExecutor(5,5,0L, TimeUnit.MILLISECONDS,newSynchronousQueue(),newThreadFactory() { @OverridepublicThread newThread(Runnable r) { Thread t =newThread(r); System.out.println("我是线程"+ r);returnt; } } );//用lambda表达式编写方法体中的逻辑Runnablerun= () -> {try{ Thread.sleep(1000); System.out.println(Thread.currentThread().getName() +"正在执行"); }catch(InterruptedException e) { e.printStackTrace(); } };for(inti =0; i <5; i++) { service.submit(run); }//这里一定要做关闭service.shutdown();}

运行代码后,控制行会输出五行 “我是线程java.util.concurrent.ThreadPoolExecutor。。。。。”的信息,也证明了我们自定义的ThreadFactory起到了作用。

每天都在分享文章,也每天都有人想要我出来给大家分享下怎么去学习Java。大家都知道,我们是学Java全栈的,大家就肯定以为我有全套的Java系统教程。没错,我是有Java全套系统教程,进扣裙【47】974【9726】所示,进群的时候记得表明自己想要学习什么,不要用小号,这样小编才好给你们发定向资源,今天小编就免费送!~

后记:对于大部分转行的人来说,找机会把自己的基础知识补齐,边工作边补基础知识,真心很重要。“我们相信人人都可以成为一个程序员,现在开始,找个师兄,带你入门,学习的路上不再迷茫。这里是ja+va修真院,初学者转行到互联网行业的聚集地。

你可能感兴趣的:(Java并发编程:Java的四种线程池的使用,以及自定义线程工厂)