|
| 1 | +### ExecutorService 的理解与使用 ### |
| 2 | +接口 java.util.concurrent.ExecutorService 表述了异步执行的机制,并且可以让任务在后台执行。一个 ExecutorService 实例因此特别像一个线程池。事实上,在 java.util.concurrent 包中的 ExecutorService 的实现就是一个线程池的实现。 |
| 3 | + |
| 4 | +#### ExecutorService 样例 #### |
| 5 | +```java |
| 6 | + ExecutorService executorService = Executors.newFixedThreadPool(10); |
| 7 | + |
| 8 | + executorService.execute(new Runnable() { |
| 9 | + public void run() { |
| 10 | + System.out.println("Asynchronous task"); |
| 11 | + } |
| 12 | + }); |
| 13 | + |
| 14 | + executorService.shutdown(); |
| 15 | +``` |
| 16 | + |
| 17 | +首先使用 newFixedThreadPool() 工厂方法创建壹個 ExecutorService ,上述代码创建了壹個可以容纳10個线程任务的线程池。其次,向 execute() 方法中传递壹個异步的 Runnable 接口的实现,这样做会让 ExecutorService 中的某個线程执行这個 Runnable 线程。 |
| 18 | + |
| 19 | +#### 任务的委托(Task Delegation) #### |
| 20 | +下方展示了一个线程的把任务委托异步执行的ExecutorService的示意图。 |
| 21 | + |
| 22 | + |
| 23 | + |
| 24 | +壹旦线程把任务委托给 ExecutorService,该线程就会继续执行与运行任务无关的其它任务。 |
| 25 | + |
| 26 | +#### ExecutorService 的实现 #### |
| 27 | +由于 ExecutorService 只是壹個接口,你壹量需要使用它,那麽就需要提供壹個该接口的实现。ExecutorService 接口在 java.util.concurrent 包中有如下实现类: |
| 28 | + |
| 29 | +* ThreadPoolExecutor |
| 30 | +* ScheduledThreadPoolExecutor |
| 31 | + |
| 32 | +#### 创建壹個 ExecutorService #### |
| 33 | +你可以根据自己的需要来创建壹個 ExecutorService ,也可以使用 Executors 工厂方法来创建壹個 ExecutorService 实例。这里有几個创建 ExecutorService 的例子: |
| 34 | + |
| 35 | +```java |
| 36 | +ExecutorService executorService1 = Executors.newSingleThreadExecutor(); |
| 37 | +ExecutorService executorService2 = Executors.newFixedThreadPool(10); |
| 38 | +ExecutorService executorService3 = Executors.newScheduledThreadPool(10); |
| 39 | +``` |
| 40 | +#### ExecutorService 使用方法 #### |
| 41 | +这里有几种不同的方式让你将任务委托给壹個 ExecutorService: |
| 42 | + |
| 43 | +* execute(Runnable) |
| 44 | +* submit(Runnable) |
| 45 | +* submit(Callable) |
| 46 | +* invokeAny(...) |
| 47 | +* invokeAll(...) |
| 48 | + |
| 49 | +我会在接下来的内容里把每個方法都看壹遍。 |
| 50 | +#### execute(Runnable) #### |
| 51 | +方法 execute(Runnable) 接收壹個 java.lang.Runnable 对象作为参数,并且以异步的方式执行它。如下是壹個使用 ExecutorService 执行 Runnable 的例子: |
| 52 | +```java |
| 53 | + ExecutorService executorService = Executors.newSingleThreadExecutor(); |
| 54 | + |
| 55 | + executorService.execute(new Runnable() { |
| 56 | + public void run() { |
| 57 | + System.out.println("Asynchronous task"); |
| 58 | + } |
| 59 | + }); |
| 60 | + |
| 61 | + executorService.shutdown(); |
| 62 | +``` |
| 63 | + |
| 64 | +使用这种方式没有办法获取执行 Runnable 之后的结果,如果你希望获取运行之后的返回值,就必须使用 接收 Callable 参数的 execute() 方法,后者将会在下文中提到。 |
| 65 | + |
| 66 | +#### submit(Runnable) #### |
| 67 | +方法 submit(Runnable) 同样接收壹個 Runnable 的实现作为参数,但是会返回壹個 Future 对象。这個 Future 对象可以用于判断 Runnable 是否结束执行。如下是壹個 ExecutorService 的 submit() 方法的例子: |
| 68 | + |
| 69 | +```java |
| 70 | + Future future = executorService.submit(new Runnable() { |
| 71 | + public void run() { |
| 72 | + System.out.println("Asynchronous task"); |
| 73 | + } |
| 74 | + }); |
| 75 | + //如果任务结束执行则返回 null |
| 76 | + System.out.println("future.get()=" + future.get()); |
| 77 | +``` |
| 78 | +上述样例代码会输出如下结果: |
| 79 | + |
| 80 | +1 Asynchronous Callable |
| 81 | + |
| 82 | +2 future.get() = Callable Result |
| 83 | + |
| 84 | +#### inVokeAny() #### |
| 85 | +方法 invokeAny() 接收壹個包含 Callable 对象的集合作为参数。调用该方法不会返回 Future 对象,而是返回集合中某壹個 Callable 对象的结果,而且无法保证调用之后返回的结果是哪壹個 Callable,只知道它是这些 Callable 中壹個执行结束的 Callable 对象。 |
| 86 | +如果壹個任务运行完毕或者抛出异常,方法会取消其它的 Callable 的执行。 |
| 87 | + |
| 88 | +以下是壹個样例: |
| 89 | + |
| 90 | +```java |
| 91 | + ExecutorService executorService = Executors.newSingleThreadExecutor(); |
| 92 | + |
| 93 | + Set<Callable<String>> callables = new HashSet<Callable<String>>(); |
| 94 | + |
| 95 | + callables.add(new Callable<String>() { |
| 96 | + public String call() throws Exception { |
| 97 | + return "Task 1"; |
| 98 | + } |
| 99 | + }); |
| 100 | + callables.add(new Callable<String>() { |
| 101 | + public String call() throws Exception { |
| 102 | + return "Task 2"; |
| 103 | + } |
| 104 | + }); |
| 105 | + callables.add(new Callable<String>() { |
| 106 | + public String call() throws Exception { |
| 107 | + return "Task 3"; |
| 108 | + } |
| 109 | + }); |
| 110 | + |
| 111 | + String result = executorService.invokeAny(callables); |
| 112 | + |
| 113 | + System.out.println("result = " + result); |
| 114 | + |
| 115 | + executorService.shutdown(); |
| 116 | +``` |
| 117 | + |
| 118 | +以上样例代码会打印出在给定的集合中的某壹個 Callable 的返回结果。我尝试运行了几次,结果都在改变。有时候返回结果是"Task 1",有时候是"Task 2",等等。 |
| 119 | + |
| 120 | +#### invokeAll() #### |
| 121 | +方法 invokeAll() 会调用存在于参数集合中的所有 Callable 对象,并且返回壹個包含 Future 对象的集合,你可以通过这個返回的集合来管理每個 Callable 的执行结果。 |
| 122 | +需要注意的是,任务有可能因为异常而导致运行结束,所以它可能并不是真的成功运行了。但是我们没有办法通过 Future 对象来了解到这個差异。 |
| 123 | + |
| 124 | +以下是壹個代码样例: |
| 125 | + |
| 126 | +```java |
| 127 | + ExecutorService executorService = Executors.newSingleThreadExecutor(); |
| 128 | + |
| 129 | + Set<Callable<String>> callables = new HashSet<Callable<String>>(); |
| 130 | + |
| 131 | + callables.add(new Callable<String>() { |
| 132 | + public String call() throws Exception { |
| 133 | + return "Task 1"; |
| 134 | + } |
| 135 | + }); |
| 136 | + callables.add(new Callable<String>() { |
| 137 | + public String call() throws Exception { |
| 138 | + return "Task 2"; |
| 139 | + } |
| 140 | + }); |
| 141 | + callables.add(new Callable<String>() { |
| 142 | + public String call() throws Exception { |
| 143 | + return "Task 3"; |
| 144 | + } |
| 145 | + }); |
| 146 | + |
| 147 | + List<Future<String>> futures = executorService.invokeAll(callables); |
| 148 | + |
| 149 | + for(Future<String> future : futures){ |
| 150 | + System.out.println("future.get = " + future.get()); |
| 151 | + } |
| 152 | + |
| 153 | + executorService.shutdown(); |
| 154 | +``` |
| 155 | + |
| 156 | +#### ExecuteService 服务的关闭 #### |
| 157 | +当使用 ExecutorService 完毕之后,我们应该关闭它,这样才能保证线程不会继续保持运行状态。 |
| 158 | + |
| 159 | +举例来说,如果你的程序通过 main() 方法启动,并且主线程退出了你的程序,如果你还有壹個活动的 ExecutorService 存在于你的程序中,那么程序将会继续保持运行状态。存在于 ExecutorService 中的活动线程会阻止Java虚拟机关闭。 |
| 160 | + |
| 161 | +为了关闭在 ExecutorService 中的线程,你需要调用 shutdown() 方法。ExecutorService 并不会马上关闭,而是不再接收新的任务,壹但所有的线程结束执行当前任务,ExecutorServie 才会真的关闭。所有在调用 shutdown() 方法之前提交到 ExecutorService 的任务都会执行。 |
| 162 | + |
| 163 | +如果你希望立即关闭 ExecutorService,你可以调用 shutdownNow() 方法。这個方法会尝试马上关闭所有正在执行的任务,并且跳过所有已经提交但是还没有运行的任务。但是对于正在执行的任务,是否能够成功关闭它是无法保证 的,有可能他们真的被关闭掉了,也有可能它会壹直执行到任务结束。这是壹個最好的尝试。 |
| 164 | + |
| 165 | +本文英文原文链接:http://tutorials.jenkov.com/java-util-concurrent/executorservice.html#executorservice-example ,中文译文首发开源中国社区 http://my.oschina.net/bairrfhoinn/blog/177639,转载请注明原始出处。 |
0 commit comments