Executor 执行 Runnable 任务
通过 Executors 的以上四个静态工厂方法获得 ExecutorService 实例,而后调用该实例的 execute(Runnable command)方法即可。一旦 Runnable 任务传递到 execute()方法,该方法便会自动在一个线程上执行。下面是 Executor 执行 Runnable 任务的示例代码:
1import java.util.concurrent.ExecutorService; 2import java.util.concurrent.Executors; 3 4public class TestCachedThreadPool{ 5 public static void main(String[] args){ 6 ExecutorService executorService = Executors.newCachedThreadPool(); 7// ExecutorService executorService = Executors.newFixedThreadPool(5); 8// ExecutorService executorService = Executors.newSingleThreadExecutor(); 9 for (int i = 0; i < 5; i++){ 10 executorService.execute(new TestRunnable()); 11 System.out.println("************* a" + i + " *************"); 12 } 13 executorService.shutdown(); 14 } 15} 16 17class TestRunnable implements Runnable{ 18 public void run(){ 19 System.out.println(Thread.currentThread().getName() + "线程被调用了。"); 20 } 21}
执行后的结果如下:

从结果中可以看出,pool-1-thread-1 和 pool-1-thread-2 均被调用了两次,这是随机的,execute 会首先在线程池中选择一个已有空闲线程来执行任务,如果线程池中没有空闲线程,它便会创建一个新的线程来执行任务。
Executor 执行 Callable 任务
在 Java 5 之后,任务分两类:一类是实现了 Runnable 接口的类,一类是实现了 Callable 接口的类。两者都可以被 ExecutorService 执行,但是 Runnable 任务没有返回值,而 Callable 任务有返回值。并且 Callable 的 call()方法只能通过 ExecutorService 的 submit(Callable task) 方法来执行,并且返回一个 Future,是表示任务等待完成的 Future。
Callable 接口类似于 Runnable,两者都是为那些其实例可能被另一个线程执行的类设计的。但是 Runnable 不会返回结果,并且无法抛出经过检查的异常而 Callable 又返回结果,而且当获取返回结果时可能会抛出异常。Callable 中的 call()方法类似 Runnable 的 run()方法,区别同样是有返回值,后者没有。
当将一个 Callable 的对象传递给 ExecutorService 的 submit 方法,则该 call 方法自动在一个线程上执行,并且会返回执行结果 Future 对象。同样,将 Runnable 的对象传递给 ExecutorService 的 submit 方法,则该 run 方法自动在一个线程上执行,并且会返回执行结果 Future 对象,但是在该 Future 对象上调用 get 方法,将返回 null。
下面给出一个 Executor 执行 Callable 任务的示例代码:
1import java.util.ArrayList; 2import java.util.List; 3import java.util.concurrent.*; 4 5public class CallableDemo{ 6 public static void main(String[] args){ 7 ExecutorService executorService = Executors.newCachedThreadPool(); 8 List<Future<String>> resultList = new ArrayList<Future<String>>(); 9 10 //创建10个任务并执行 11 for (int i = 0; i < 10; i++){ 12 //使用ExecutorService执行Callable类型的任务,并将结果保存在future变量中 13 Future<String> future = executorService.submit(new TaskWithResult(i)); 14 //将任务执行结果存储到List中 15 resultList.add(future); 16 } 17 18 //遍历任务的结果 19 for (Future<String> fs : resultList){ 20 try{ 21 while(!fs.isDone);//Future返回如果没有完成,则一直循环等待,直到Future返回完成 22 System.out.println(fs.get()); //打印各个线程(任务)执行的结果 23 }catch(InterruptedException e){ 24 e.printStackTrace(); 25 }catch(ExecutionException e){ 26 e.printStackTrace(); 27 }finally{ 28 //启动一次顺序关闭,执行以前提交的任务,但不接受新任务 29 executorService.shutdown(); 30 } 31 } 32 } 33} 34 35class TaskWithResult implements Callable<String>{ 36 private int id; 37 38 public TaskWithResult(int id){ 39 this.id = id; 40 } 41 42 /** 43 * 任务的具体过程,一旦任务传给ExecutorService的submit方法, 44 * 则该方法自动在一个线程上执行 45 */ 46 public String call() throws Exception { 47 System.out.println("call()方法被自动调用!!! " + Thread.currentThread().getName()); 48 //该返回结果将被Future的get方法得到 49 return "call()方法被自动调用,任务返回的结果是:" + id + " " + Thread.currentThread().getName(); 50 } 51}
执行结果如下:

从结果中可以同样可以看出,submit 也是首先选择空闲线程来执行任务,如果没有,才会创建新的线程来执行任务。另外,需要注意:如果 Future 的返回尚未完成,则 get()方法会阻塞等待,直到 Future 完成返回,可以通过调用 isDone()方法判断 Future 是否完成了返回。
自定义线程池
自定义线程池,可以用 ThreadPoolExecutor 类创建,它有多个构造方法来创建线程池,用该类很容易实现自定义的线程池,这里先贴上示例程序:
1import java.util.concurrent.ArrayBlockingQueue; 2import java.util.concurrent.BlockingQueue; 3import java.util.concurrent.ThreadPoolExecutor; 4import java.util.concurrent.TimeUnit; 5 6public class ThreadPoolTest{ 7 public static void main(String[] args){ 8 //创建等待队列 9 BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue<Runnable>(20); 10 //创建线程池,池中保存的线程数为3,允许的最大线程数为5 11 ThreadPoolExecutor pool = new ThreadPoolExecutor(3,5,50,TimeUnit.MILLISECONDS,bqueue); 12 //创建七个任务 13 Runnable t1 = new MyThread(); 14 Runnable t2 = new MyThread(); 15 Runnable t3 = new MyThread(); 16 Runnable t4 = new MyThread(); 17 Runnable t5 = new MyThread(); 18 Runnable t6 = new MyThread(); 19 Runnable t7 = new MyThread(); 20 //每个任务会在一个线程上执行 21 pool.execute(t1); 22 pool.execute(t2); 23 pool.execute(t3); 24 pool.execute(t4); 25 pool.execute(t5); 26 pool.execute(t6); 27 pool.execute(t7); 28 //关闭线程池 29 pool.shutdown(); 30 } 31} 32 33class MyThread implements Runnable{ 34 @Override 35 public void run(){ 36 System.out.println(Thread.currentThread().getName() + "正在执行。。。"); 37 try{ 38 Thread.sleep(100); 39 }catch(InterruptedException e){ 40 e.printStackTrace(); 41 } 42 } 43}
运行结果如下:

从结果中可以看出,七个任务是在线程池的三个线程上执行的。这里简要说明下用到的 ThreadPoolExecuror 类的构造方法中各个参数的含义。
public ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue)
-
corePoolSize:线程池中所保存的核心线程数,包括空闲线程。
-
maximumPoolSize:池中允许的最大线程数。
-
keepAliveTime:线程池中的空闲线程所能持续的最长时间。
-
unit:持续时间的单位。
-
workQueue:任务执行前保存任务的队列,仅保存由 execute 方法提交的 Runnable 任务。
根据 ThreadPoolExecutor 源码前面大段的注释,我们可以看出,当试图通过 excute 方法讲一个 Runnable 任务添加到线程池中时,按照如下顺序来处理:
-
如果线程池中的线程数量少于 corePoolSize,即使线程池中有空闲线程,也会创建一个新的线程来执行新添加的任务;
-
如果线程池中的线程数量大于等于 corePoolSize,但缓冲队列 workQueue 未满,则将新添加的任务放到 workQueue 中,按照 FIFO 的原则依次等待执行(线程池中有线程空闲出来后依次将缓冲队列中的任务交付给空闲的线程执行);
-
如果线程池中的线程数量大于等于 corePoolSize,且缓冲队列 workQueue 已满,但线程池中的线程数量小于 maximumPoolSize,则会创建新的线程来处理被添加的任务;
-
如果线程池中的线程数量等于了 maximumPoolSize,有 4 种才处理方式(该构造方法调用了含有 5 个参数的构造方法,并将最后一个构造方法为 RejectedExecutionHandler 类型,它在处理线程溢出时有 4 种方式,这里不再细说,要了解的,自己可以阅读下源码)。
总结起来,也即是说,当有新的任务要处理时,先看线程池中的线程数量是否大于 corePoolSize,再看缓冲队列 workQueue 是否满,最后看线程池中的线程数量是否大于 maximumPoolSize。
另外,当线程池中的线程数量大于 corePoolSize 时,如果里面有线程的空闲时间超过了 keepAliveTime,就将其移除线程池,这样,可以动态地调整线程池中线程的数量。
我们大致来看下 Executors 的源码,newCachedThreadPool 的不带 RejectedExecutionHandler 参数(即第五个参数,线程数量超过 maximumPoolSize 时,指定处理方式)的构造方法如下:
1public static ExecutorService newCachedThreadPool() { 2 return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 3 60L, TimeUnit.SECONDS, 4 new SynchronousQueue<Runnable>()); 5}
它将 corePoolSize 设定为 0,而将 maximumPoolSize 设定为了 Integer 的最大值,线程空闲超过 60 秒,将会从线程池中移除。由于核心线程数为 0,因此每次添加任务,都会先从线程池中找空闲线程,如果没有就会创建一个线程(SynchronousQueue决定的,后面会说)来执行新的任务,并将该线程加入到线程池中,而最大允许的线程数为 Integer 的最大值,因此这个线程池理论上可以不断扩大。
再来看 newFixedThreadPool 的不带 RejectedExecutionHandler 参数的构造方法,如下:
1public static ExecutorService newFixedThreadPool(int nThreads) { 2 return new ThreadPoolExecutor(nThreads, nThreads, 3 0L, TimeUnit.MILLISECONDS, 4 new LinkedBlockingQueue<Runnable>()); 5}
它将 corePoolSize 和 maximumPoolSize 都设定为了 nThreads,这样便实现了线程池的大小的固定,不会动态地扩大,另外,keepAliveTime 设定为了 0,也就是说线程只要空闲下来,就会被移除线程池,敢于 LinkedBlockingQueue 下面会说。
几种排队的策略
-
直接提交。缓冲队列采用 SynchronousQueue,它将任务直接交给线程处理而不保持它们。如果不存在可用于立即运行任务的线程(即线程池中的线程都在工作),则试图把任务加入缓冲队列将会失败,因此会构造一个新的线程来处理新添加的任务,并将其加入到线程池中。直接提交通常要求无界 maximumPoolSizes(Integer.MAX_VALUE) 以避免拒绝新提交的任务。newCachedThreadPool 采用的便是这种策略。
-
无界队列。使用无界队列(典型的便是采用预定义容量的 LinkedBlockingQueue,理论上是该缓冲队列可以对无限多的任务排队)将导致在所有 corePoolSize 线程都工作的情况下将新任务加入到缓冲队列中。这样,创建的线程就不会超过 corePoolSize,也因此,maximumPoolSize 的值也就无效了。当每个任务完全独立于其他任务,即任务执行互不影响时,适合于使用无界队列。newFixedThreadPool采用的便是这种策略。
-
有界队列。当使用有限的 maximumPoolSizes 时,有界队列(一般缓冲队列使用 ArrayBlockingQueue,并制定队列的最大长度)有助于防止资源耗尽,但是可能较难调整和控制,队列大小和最大池大小需要相互折衷,需要设定合理的参数。