|
| 1 | +> 原文链接:Mr.Simple,http://blog.csdn.net/bboyfeiyu/article/details/24851847 |
| 2 | +
|
| 3 | +Java中存在Runnable、Callable、Future、FutureTask这几个与线程相关的类或者接口,在Java中也是比较重要的几个概念,我们通过下面的简单示例来了解一下它们的作用于区别。 |
| 4 | + |
| 5 | +## Runnable |
| 6 | +其中Runnable应该是我们最熟悉的接口,它只有一个run()函数,用于将耗时操作写在其中,该函数没有返回值。然后使用某个线程去执行该runnable即可实现多线程,Thread类在调用start()函数后就是执行的是Runnable的run()函数。Runnable的声明如下 : |
| 7 | +```java |
| 8 | +public interface Runnable { |
| 9 | + /** |
| 10 | + * When an object implementing interface <code>Runnable</code> is used |
| 11 | + * to create a thread, starting the thread causes the object's |
| 12 | + * <code>run</code> method to be called in that separately executing |
| 13 | + * thread. |
| 14 | + * <p> |
| 15 | + * |
| 16 | + * @see java.lang.Thread#run() |
| 17 | + */ |
| 18 | + public abstract void run(); |
| 19 | +} |
| 20 | +``` |
| 21 | +## Callable |
| 22 | +Callable与Runnable的功能大致相似,Callable中有一个call()函数,但是call()函数有返回值,而Runnable的run()函数不能将结果返回给客户程序。Callable的声明如下 : |
| 23 | +```java |
| 24 | +public interface Callable<V> { |
| 25 | + /** |
| 26 | + * Computes a result, or throws an exception if unable to do so. |
| 27 | + * |
| 28 | + * @return computed result |
| 29 | + * @throws Exception if unable to compute a result |
| 30 | + */ |
| 31 | + V call() throws Exception; |
| 32 | +} |
| 33 | +``` |
| 34 | +可以看到,这是一个泛型接口,call()函数返回的类型就是客户程序传递进来的V类型。 |
| 35 | +## Future |
| 36 | +Executor就是Runnable和Callable的调度容器,Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果、设置结果操作。get方法会阻塞,直到任务返回结果(Future简介)。Future声明如下 : |
| 37 | +```java |
| 38 | +/** |
| 39 | +* @see FutureTask |
| 40 | + * @see Executor |
| 41 | + * @since 1.5 |
| 42 | + * @author Doug Lea |
| 43 | + * @param <V> The result type returned by this Future's <tt>get</tt> method |
| 44 | + */ |
| 45 | +public interface Future<V> { |
| 46 | + |
| 47 | + /** |
| 48 | + * Attempts to cancel execution of this task. This attempt will |
| 49 | + * fail if the task has already completed, has already been cancelled, |
| 50 | + * or could not be cancelled for some other reason. If successful, |
| 51 | + * and this task has not started when <tt>cancel</tt> is called, |
| 52 | + * this task should never run. If the task has already started, |
| 53 | + * then the <tt>mayInterruptIfRunning</tt> parameter determines |
| 54 | + * whether the thread executing this task should be interrupted in |
| 55 | + * an attempt to stop the task. * |
| 56 | + */ |
| 57 | + boolean cancel(boolean mayInterruptIfRunning); |
| 58 | + |
| 59 | + /** |
| 60 | + * Returns <tt>true</tt> if this task was cancelled before it completed |
| 61 | + * normally. |
| 62 | + */ |
| 63 | + boolean isCancelled(); |
| 64 | + |
| 65 | + /** |
| 66 | + * Returns <tt>true</tt> if this task completed. |
| 67 | + * |
| 68 | + */ |
| 69 | + boolean isDone(); |
| 70 | + |
| 71 | + /** |
| 72 | + * Waits if necessary for the computation to complete, and then |
| 73 | + * retrieves its result. |
| 74 | + * |
| 75 | + * @return the computed result |
| 76 | + */ |
| 77 | + V get() throws InterruptedException, ExecutionException; |
| 78 | + |
| 79 | + /** |
| 80 | + * Waits if necessary for at most the given time for the computation |
| 81 | + * to complete, and then retrieves its result, if available. |
| 82 | + * |
| 83 | + * @param timeout the maximum time to wait |
| 84 | + * @param unit the time unit of the timeout argument |
| 85 | + * @return the computed result |
| 86 | + */ |
| 87 | + V get(long timeout, TimeUnit unit) |
| 88 | + throws InterruptedException, ExecutionException, TimeoutException; |
| 89 | +} |
| 90 | +``` |
| 91 | +## FutureTask |
| 92 | +FutureTask则是一个RunnableFuture<V>,而RunnableFuture实现了Runnbale又实现了Futrue<V>这两个接口, |
| 93 | +```java |
| 94 | +public class FutureTask<V> implements RunnableFuture<V> |
| 95 | +``` |
| 96 | +RunnableFuture |
| 97 | +```java |
| 98 | +public interface RunnableFuture<V> extends Runnable, Future<V> { |
| 99 | + /** |
| 100 | + * Sets this Future to the result of its computation |
| 101 | + * unless it has been cancelled. |
| 102 | + */ |
| 103 | + void run(); |
| 104 | +} |
| 105 | +``` |
| 106 | +另外它还可以包装Runnable和Callable<V>, 由构造函数注入依赖。 |
| 107 | +```java |
| 108 | +public FutureTask(Callable<V> callable) { |
| 109 | + if (callable == null) |
| 110 | + throw new NullPointerException(); |
| 111 | + this.callable = callable; |
| 112 | + this.state = NEW; // ensure visibility of callable |
| 113 | +} |
| 114 | + |
| 115 | +public FutureTask(Runnable runnable, V result) { |
| 116 | + this.callable = Executors.callable(runnable, result); |
| 117 | + this.state = NEW; // ensure visibility of callable |
| 118 | +} |
| 119 | +``` |
| 120 | +可以看到,Runnable注入会被Executors.callable()函数转换为Callable类型,即FutureTask最终都是执行Callable类型的任务。该适配函数的实现如下 : |
| 121 | +```java |
| 122 | +public static <T> Callable<T> callable(Runnable task, T result) { |
| 123 | + if (task == null) |
| 124 | + throw new NullPointerException(); |
| 125 | + return new RunnableAdapter<T>(task, result); |
| 126 | +} |
| 127 | +``` |
| 128 | +RunnableAdapter适配器 |
| 129 | +```java |
| 130 | +/** |
| 131 | + * A callable that runs given task and returns given result |
| 132 | + */ |
| 133 | +static final class RunnableAdapter<T> implements Callable<T> { |
| 134 | + final Runnable task; |
| 135 | + final T result; |
| 136 | + RunnableAdapter(Runnable task, T result) { |
| 137 | + this.task = task; |
| 138 | + this.result = result; |
| 139 | + } |
| 140 | + public T call() { |
| 141 | + task.run(); |
| 142 | + return result; |
| 143 | + } |
| 144 | +} |
| 145 | +``` |
| 146 | +由于FutureTask实现了Runnable,因此它既可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行。并且还可以直接通过get()函数获取执行结果,该函数会阻塞,直到结果返回。因此FutureTask既是Future、Runnable,又是包装了Callable( 如果是Runnable最终也会被转换为Callable ), 它是这两者的合体。 |
| 147 | + |
| 148 | +简单示例 |
| 149 | + |
| 150 | +```java |
| 151 | + package com.effective.java.concurrent.task; |
| 152 | + |
| 153 | +import java.util.concurrent.Callable; |
| 154 | +import java.util.concurrent.ExecutionException; |
| 155 | +import java.util.concurrent.ExecutorService; |
| 156 | +import java.util.concurrent.Executors; |
| 157 | +import java.util.concurrent.Future; |
| 158 | +import java.util.concurrent.FutureTask; |
| 159 | + |
| 160 | +/** |
| 161 | + * |
| 162 | + * @author mrsimple |
| 163 | + * |
| 164 | + */ |
| 165 | +public class RunnableFutureTask { |
| 166 | + |
| 167 | + /** |
| 168 | + * ExecutorService |
| 169 | + */ |
| 170 | + static ExecutorService mExecutor = Executors.newSingleThreadExecutor(); |
| 171 | + |
| 172 | + /** |
| 173 | + * |
| 174 | + * @param args |
| 175 | + */ |
| 176 | + public static void main(String[] args) { |
| 177 | + runnableDemo(); |
| 178 | + futureDemo(); |
| 179 | + } |
| 180 | + |
| 181 | + /** |
| 182 | + * runnable, 无返回值 |
| 183 | + */ |
| 184 | + static void runnableDemo() { |
| 185 | + |
| 186 | + new Thread(new Runnable() { |
| 187 | + |
| 188 | + @Override |
| 189 | + public void run() { |
| 190 | + System.out.println("runnable demo : " + fibc(20)); |
| 191 | + } |
| 192 | + }).start(); |
| 193 | + } |
| 194 | + |
| 195 | + /** |
| 196 | + * 其中Runnable实现的是void run()方法,无返回值;Callable实现的是 V |
| 197 | + * call()方法,并且可以返回执行结果。其中Runnable可以提交给Thread来包装下 |
| 198 | + * ,直接启动一个线程来执行,而Callable则一般都是提交给ExecuteService来执行。 |
| 199 | + */ |
| 200 | + static void futureDemo() { |
| 201 | + try { |
| 202 | + /** |
| 203 | + * 提交runnable则没有返回值, future没有数据 |
| 204 | + */ |
| 205 | + Future<?> result = mExecutor.submit(new Runnable() { |
| 206 | + |
| 207 | + @Override |
| 208 | + public void run() { |
| 209 | + fibc(20); |
| 210 | + } |
| 211 | + }); |
| 212 | + |
| 213 | + System.out.println("future result from runnable : " + result.get()); |
| 214 | + |
| 215 | + /** |
| 216 | + * 提交Callable, 有返回值, future中能够获取返回值 |
| 217 | + */ |
| 218 | + Future<Integer> result2 = mExecutor.submit(new Callable<Integer>() { |
| 219 | + @Override |
| 220 | + public Integer call() throws Exception { |
| 221 | + return fibc(20); |
| 222 | + } |
| 223 | + }); |
| 224 | + |
| 225 | + System.out |
| 226 | + .println("future result from callable : " + result2.get()); |
| 227 | + |
| 228 | + /** |
| 229 | + * FutureTask则是一个RunnableFuture<V>,即实现了Runnbale又实现了Futrue<V>这两个接口, |
| 230 | + * 另外它还可以包装Runnable(实际上会转换为Callable)和Callable |
| 231 | + * <V>,所以一般来讲是一个符合体了,它可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行 |
| 232 | + * ,并且还可以通过v get()返回执行结果,在线程体没有执行完成的时候,主线程一直阻塞等待,执行完则直接返回结果。 |
| 233 | + */ |
| 234 | + FutureTask<Integer> futureTask = new FutureTask<Integer>( |
| 235 | + new Callable<Integer>() { |
| 236 | + @Override |
| 237 | + public Integer call() throws Exception { |
| 238 | + return fibc(20); |
| 239 | + } |
| 240 | + }); |
| 241 | + // 提交futureTask |
| 242 | + mExecutor.submit(futureTask) ; |
| 243 | + System.out.println("future result from futureTask : " |
| 244 | + + futureTask.get()); |
| 245 | + |
| 246 | + } catch (InterruptedException e) { |
| 247 | + e.printStackTrace(); |
| 248 | + } catch (ExecutionException e) { |
| 249 | + e.printStackTrace(); |
| 250 | + } |
| 251 | + } |
| 252 | + |
| 253 | + /** |
| 254 | + * 效率底下的斐波那契数列, 耗时的操作 |
| 255 | + * |
| 256 | + * @param num |
| 257 | + * @return |
| 258 | + */ |
| 259 | + static int fibc(int num) { |
| 260 | + if (num == 0) { |
| 261 | + return 0; |
| 262 | + } |
| 263 | + if (num == 1) { |
| 264 | + return 1; |
| 265 | + } |
| 266 | + return fibc(num - 1) + fibc(num - 2); |
| 267 | + } |
| 268 | + |
| 269 | +} |
| 270 | +``` |
| 271 | +输出结果 |
| 272 | + |
| 273 | + |
0 commit comments