java中线程池创建的几种方式
java中创建线程池的方式一般有两种:
- 通过Executors工厂方法创建
- 通过new
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)自定义创建
Executors工厂方法创建
package com.javaBase.LineDistancePond; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * 〈一句话功能简述〉; * 〈功能详细描述〉 * * @author jxx * @see [相关类/方法](可选) * @since [产品/模块版本] (可选) */ public class TestThreadPoolExecutor { public static void main(String[] args) { //创建使用单个线程的线程池 ExecutorService es1 = Executors.newSingleThreadExecutor(); for (int i = 0; i < 10; i++) { es1.submit(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + "正在执行任务"); } }); } //创建使用固定线程数的线程池 ExecutorService es2 = Executors.newFixedThreadPool(3); for (int i = 0; i < 10; i++) { es2.submit(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + "正在执行任务"); } }); } //创建一个会根据需要创建新线程的线程池 ExecutorService es3 = Executors.newCachedThreadPool(); for (int i = 0; i < 20; i++) { es3.submit(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + "正在执行任务"); } }); } //创建拥有固定线程数量的定时线程任务的线程池 ScheduledExecutorService es4 = Executors.newScheduledThreadPool(2); System.out.println("时间:" + System.currentTimeMillis()); for (int i = 0; i < 5; i++) { es4.schedule(new Runnable() { @Override public void run() { System.out.println("时间:"+System.currentTimeMillis()+"--"+Thread.currentThread().getName() + "正在执行任务"); } },3, TimeUnit.SECONDS); } //创建只有一个线程的定时线程任务的线程池 ScheduledExecutorService es5 = Executors.newSingleThreadScheduledExecutor(); System.out.println("时间:" + System.currentTimeMillis()); for (int i = 0; i < 5; i++) { es5.schedule(new Runnable() { @Override public void run() { System.out.println("时间:"+System.currentTimeMillis()+"--"+Thread.currentThread().getName() + "正在执行任务"); } },3, TimeUnit.SECONDS); } } }
new ThreadPoolExecutor()自定义创建
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler) ;
corePoolSize:核心池的大小,这个参数跟后面讲述的线程池的实现原理有非常大的关系。在创建了线程池后,默认情况下,线程池中并没有任何线程,而是等待有任务到来才创建线程去执行任务,除非调用了prestartAllCoreThreads()或者prestartCoreThread()方法,从这2个方法的名字就可以看出,是预创建线程的意思,即在没有任务到来之前就创建corePoolSize个线程或者一个线程。默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中;
maximumPoolSize:线程池最大线程数,这个参数也是一个非常重要的参数,它表示在线程池中最多能创建多少个线程;
keepAliveTime:表示线程没有任务执行时最多保持多久时间会终止。默认情况下,只有当线程池中的线程数大于corePoolSize时,keepAliveTime才会起作用,直到线程池中的线程数不大于corePoolSize,即当线程池中的线程数大于corePoolSize时,如果一个线程空闲的时间达到keepAliveTime,则会终止,直到线程池中的线程数不超过corePoolSize。但是如果调用了allowCoreThreadTimeOut(boolean)方法,在线程池中的线程数不大于corePoolSize时,keepAliveTime参数也会起作用,直到线程池中的线程数为0;
unit:参数keepAliveTime的时间单位,有7种取值,在TimeUnit类中有7种静态属性:TimeUnit.DAYS; //天 TimeUnit.HOURS; //小时 TimeUnit.MINUTES; //分钟 TimeUnit.SECONDS; //秒 TimeUnit.MILLISECONDS; //毫秒 TimeUnit.MICROSECONDS; //微妙 TimeUnit.NANOSECONDS; //纳秒
workQueue:一个阻塞队列,用来存储等待执行的任务,这个参数的选择也很重要,会对线程池的运行过程产生重大影响,一般来说,这里的阻塞队列有以下几种选择:
ArrayBlockingQueue
LinkedBlockingQueue
SynchronousQueue
PriorityBlockingQueue
ArrayBlockingQueue和PriorityBlockingQueue使用较少,一般使用LinkedBlockingQueue和SynchronousQueue。线程池的排队策略与BlockingQueue有关。
threadFactory:用于设置创建线程的工厂,可以通过线程工厂给每个创建出来的线程做些更有意义的事情,比如设置daemon和优先级等等
handler:表示当拒绝处理任务时的策略,有以下四种取值:
1、AbortPolicy:直接抛出异常。 2、CallerRunsPolicy:只用调用者所在线程来运行任务。 3、DiscardOldestPolicy:丢弃队列里最近的一个任务,并执行当前任务。 4、DiscardPolicy:不处理,丢弃掉。 5、也可以根据应用场景需要来实现RejectedExecutionHandler接口自定义策略。如记录日志或持久化不能处理的任务。
ThreadPoolExecutor 源码理解
public static void test(int size) { ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 20, 2, TimeUnit.SECONDS, new LinkedBlockingQueue<>(5)); for (int i = 0; i < size; i++) { poolExecutor.execute(new DemoTask(i)); Console.log("poolSize:" + poolExecutor.getPoolSize()); Console.log("corePoolSize:" + poolExecutor.getCorePoolSize()); Console.log("maximumPoolSize:" + poolExecutor.getMaximumPoolSize()); Console.log("queue:" + poolExecutor.getQueue().size()); Console.log("completedTaskCount:" + poolExecutor.getCompletedTaskCount()); Console.log("largestPoolSize:" + poolExecutor.getLargestPoolSize()); Console.log("keepAliveTime:" + poolExecutor.getKeepAliveTime(TimeUnit.SECONDS)); } poolExecutor.shutdown(); } class DemoTask implements Runnable { private int taskNum; public DemoTask(int taskNum) { this.taskNum = taskNum; } @Override public void run() { Console.log(StringUtils.center("正在执行" + taskNum, 20, "=")); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } Console.log(StringUtils.center("执行完毕" + taskNum, 20, "=")); } }
执行结果:
=======正在执行0======== poolSize:1 corePoolSize:5 maximumPoolSize:20 queue:0 completedTaskCount:0 largestPoolSize:1 keepAliveTime:2 poolSize:2 corePoolSize:5 maximumPoolSize:20 queue:0 completedTaskCount:0 =======正在执行1======== largestPoolSize:2 keepAliveTime:2 poolSize:3 corePoolSize:5 maximumPoolSize:20 =======正在执行2======== queue:0 completedTaskCount:0 largestPoolSize:3 keepAliveTime:2 poolSize:4 corePoolSize:5 maximumPoolSize:20 queue:0 =======正在执行3======== completedTaskCount:0 largestPoolSize:4 keepAliveTime:2 poolSize:5 corePoolSize:5 =======正在执行4======== maximumPoolSize:20 queue:0 completedTaskCount:0 largestPoolSize:5 keepAliveTime:2 poolSize:5 corePoolSize:5 maximumPoolSize:20 queue:1 completedTaskCount:0 largestPoolSize:5 keepAliveTime:2 poolSize:5 corePoolSize:5 maximumPoolSize:20 queue:2 completedTaskCount:0 largestPoolSize:5 keepAliveTime:2 poolSize:5 corePoolSize:5 maximumPoolSize:20 queue:3 completedTaskCount:0 largestPoolSize:5 keepAliveTime:2 poolSize:5 corePoolSize:5 maximumPoolSize:20 queue:4 completedTaskCount:0 largestPoolSize:5 keepAliveTime:2 poolSize:5 corePoolSize:5 maximumPoolSize:20 queue:5 completedTaskCount:0 largestPoolSize:5 keepAliveTime:2 poolSize:6 corePoolSize:5 maximumPoolSize:20 queue:5 completedTaskCount:0 largestPoolSize:6 keepAliveTime:2 poolSize:7 corePoolSize:5 maximumPoolSize:20 queue:5 completedTaskCount:0 largestPoolSize:7 keepAliveTime:2 =======正在执行11======= poolSize:8 corePoolSize:5 maximumPoolSize:20 queue:5 completedTaskCount:0 =======正在执行12======= =======正在执行10======= largestPoolSize:8 keepAliveTime:2 poolSize:9 corePoolSize:5 =======正在执行13======= maximumPoolSize:20 queue:5 completedTaskCount:0 largestPoolSize:9 keepAliveTime:2 poolSize:10 corePoolSize:5 maximumPoolSize:20 =======正在执行14======= queue:5 completedTaskCount:0 largestPoolSize:10 keepAliveTime:2 poolSize:11 corePoolSize:5 maximumPoolSize:20 queue:5 =======正在执行15======= completedTaskCount:0 largestPoolSize:11 keepAliveTime:2 poolSize:12 corePoolSize:5 maximumPoolSize:20 queue:5 completedTaskCount:0 =======正在执行16======= largestPoolSize:12 keepAliveTime:2 poolSize:13 corePoolSize:5 maximumPoolSize:20 =======正在执行17======= queue:5 completedTaskCount:0 largestPoolSize:13 keepAliveTime:2 poolSize:14 corePoolSize:5 maximumPoolSize:20 queue:5 =======正在执行18======= completedTaskCount:0 largestPoolSize:14 keepAliveTime:2 poolSize:15 corePoolSize:5 maximumPoolSize:20 =======正在执行19======= queue:5 completedTaskCount:0 largestPoolSize:15 keepAliveTime:2 =======执行完毕0======== =======正在执行5======== =======执行完毕1======== =======执行完毕2======== =======正在执行6======== =======正在执行7======== =======执行完毕4======== =======正在执行8======== =======执行完毕3======== =======正在执行9======== =======执行完毕13======= =======执行完毕12======= =======执行完毕10======= =======执行完毕11======= =======执行完毕15======= =======执行完毕16======= =======执行完毕14======= =======执行完毕19======= =======执行完毕18======= =======执行完毕17======= =======执行完毕5======== =======执行完毕7======== =======执行完毕6======== =======执行完毕8======== =======执行完毕9========
参考链接:Java线程池(一)