Java中的Runnable、Callable、Future、FutureTask的区别和CompletionService的使用场景
2016-10-24 16:17
411 查看
Java中存在Runnable、Callable、Future、FutureTask这几个与线程相关的类或者接口,在Java中也是比较重要的几个概念,我们通过下面的简单示例来了解一下它们的作用于区别。
可以看到,这是一个泛型接口,call()函数返回的类型就是客户程序传递进来的V类型。
FutureTask
FutureTask则是一个RunnableFuture< V>,而RunnableFuture实现了Runnbale又实现了Futrue< V>这两个接口:
RunnableFuture
另外FutureTask还可以包装Runnable和Callable< V>, 由构造函数注入依赖。
可以看到,Runnable注入会被Executors.callable()函数转换为Callable类型,即FutureTask最终都是执行Callable类型的任务。该适配函数的实现如下 :
RunnableAdapter适配器
由于FutureTask实现了Runnable,因此它既可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行。并且还可以直接通过get()函数获取执行结果,该函数会阻塞,直到结果返回。
因此FutureTask既是Future、Runnable,又是包装了Callable(如果是Runnable最终也会被转换为Callable ), 它是这两者的合体。
完整示例:
如果向Executor提交了一组计算任务,并且希望在计算完成后获得结果,那么可以保留与每个任务关联的Future,然后反复使用get方法,同时将参数timeout指定为0,从而通过轮询来判断任务是否完成。这种方法虽然可行,但却有些繁琐。幸运的是,还有一种更好的方法:完成服务CompletionService。
CompleteService接口是为了方便多个任务执行时,可以方便得获取到执行任务的Future结果。接口内容如下:
这五个方法分为两大方面。一个是对Callable和Runnable类型参数的任务提交,另一方面则是尝试对结果以不同的方式进行获取,take()方法一般是阻塞式的获取,后两者则更灵活。
通常来讲,CompleteService是要和Executor结合在一起使用的。
这个实现类主要做的事就是将执行完成的任务结果放到阻塞队列中,这样等待结果的线程,如果执行take()方法会得到结果并恢复执行。
ExecutorCompletionService有3个属性:
AbstractExecutorService类的对象aes
Executor类的对象executor
通常,如果executor是AbstractExecutorService的一个实现,则将其赋值给aes属性,否则赋值为null。
在这个类中,executor负责执行任务,而aes则负责做适配处理,返回包装好任务的FutureTask对象。
这里面有一个对于实现功能很重要的内部类QueueingFuture,实现如下:
QueueingFuture是FutureTask的一个子类,通过扩展该子类的done方法,可以实现当任务完成时,将结果放入到BlockingQueue中。
而通过使用BlockingQueue的take或poll方法,则可以得到结果。在BlockingQueue不存在元素时,这两个操作会阻塞,一旦有结果加入,则立即返回。
下面我们通过例子来体验下CompletionService的好处与使用场景。
首先定义一个实现了Callable接口的Task类:
1)自己维护一个list保存submit的callable task所返回的Future对象。在主线程中遍历集合并调用Future的get()方法取到Task的返回值。如下代码所示:
输出结果如下:
从输出结果可以看出,我们只能一个一个阻塞的取出。这中间肯定会浪费一定的时间在等待上。如5返回了,但是前面的1-4都没有返回,那么5就得等1-4输出才能输出。
2)通过CompletionService包装ExecutorService,然后调用其take()方法去取Future对象。如下代码所示:
输出结果如下:
可以看出,结果的输出和线程的放入顺序无关系。每一个线程执行成功后,立刻就输出。如5返回了,不管前面的1-4有没有返回,5马上输出,不管它们加入线程池的顺序,从而节省时间。
使用CompletionService来维护处理线程的返回结果时,主线程总是能够拿到最先完成的任务的返回值,而不管它们加入线程池的顺序。
CompletionService的实现是维护了一个保存Future的BlockingQueque。只有当这个Future的任务状态是结束的时候,才会加入到这个Queque中,take()方法其实就是Producer-Consumer中的Consumer。它会从Queue中取出Future对象,如果Queue是空的,就会阻塞在那里,直到有完成的Future对象加入到Queue中。也就是先完成的必定先被取出,这样就减少了不必要的等待时间。
Runnable
其中Runnable应该是我们最熟悉的接口,它只有一个run()函数,用于将耗时操作写在其中,该函数没有返回值。然后使用某个线程去执行该runnable即可实现多线程,Thread类在调用start()函数后就是执行的是Runnable的run()函数。Runnable的声明如下 :@FunctionalInterface public interface Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run(); }
Callable
Callable与Runnable的功能大致相似,Callable中有一个call()函数,但是call()函数有返回值,而Runnable的run()函数不能将结果返回给客户程序。Callable的声明如下 :@FunctionalInterface public interface Callable<V> { /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ V call() throws Exception; }
可以看到,这是一个泛型接口,call()函数返回的类型就是客户程序传递进来的V类型。
Future
Executor就是Runnable和Callable的调度容器,Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果、设置结果操作。get方法会阻塞,直到任务返回结果(Future简介)。Future声明如下:* @see FutureTask * @see Executor * @since 1.5 * @author Doug Lea * @param <V> The result type returned by this Future's {@code get} method */ public interface Future<V> { /** * Attempts to cancel execution of this task. This attempt will * fail if the task has already completed, has already been cancelled, * or could not be cancelled for some other reason. If successful, * and this task has not started when {@code cancel} is called, * this task should never run. If the task has already started, * then the {@code mayInterruptIfRunning} parameter determines * whether the thread executing this task should be interrupted in * an attempt to stop the task. * * <p>After this method returns, subsequent calls to {@link #isDone} will * always return {@code true}. Subsequent calls to {@link #isCancelled} * will always return {@code true} if this method returned {@code true}. * * @param mayInterruptIfRunning {@code true} if the thread executing this * task should be interrupted; otherwise, in-progress tasks are allowed * to complete * @return {@code false} if the task could not be cancelled, * typically because it has already completed normally; * {@code true} otherwise */ boolean cancel(boolean mayInterruptIfRunning); /** * Returns {@code true} if this task was cancelled before it completed * normally. * * @return {@code true} if this task was cancelled before it completed */ boolean isCancelled(); /** * Returns {@code true} if this task completed. * * Completion may be due to normal termination, an exception, or * cancellation -- in all of these cases, this method will return * {@code true}. * * @return {@code true} if this task completed */ boolean isDone(); /** * Waits if necessary for the computation to complete, and then * retrieves its result. * * @return the computed result * @throws CancellationException if the computation was cancelled * @throws ExecutionException if the computation threw an * exception * @throws InterruptedException if the current thread was interrupted * while waiting */ V get() throws InterruptedException, ExecutionException; /** * Waits if necessary for at most the given time for the computation * to complete, and then retrieves its result, if available. * * @param timeout the maximum time to wait * @param unit the time unit of the timeout argument * @return the computed result * @throws CancellationException if the computation was cancelled * @throws ExecutionException if the computation threw an * exception * @throws InterruptedException if the current thread was interrupted * while waiting * @throws TimeoutException if the wait timed out */ V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
FutureTask
FutureTask则是一个RunnableFuture< V>,而RunnableFuture实现了Runnbale又实现了Futrue< V>这两个接口:
public class FutureTask<V> implements RunnableFuture<V> { ...... }
RunnableFuture
/** * A {@link Future} that is {@link Runnable}. Successful execution of * the {@code run} method causes completion of the {@code Future} * and allows access to its results. * @see FutureTask * @see Executor * @since 1.6 * @author Doug Lea * @param <V> The result type returned by this Future's {@code get} method */ public interface RunnableFuture<V> extends Runnable, Future<V> { /** * Sets this Future to the result of its computation * unless it has been cancelled. */ void run(); }
另外FutureTask还可以包装Runnable和Callable< V>, 由构造函数注入依赖。
/** * Creates a {@code FutureTask} that will, upon running, execute the * given {@code Callable}. * * @param callable the callable task * @throws NullPointerException if the callable is null */ public FutureTask(Callable<V> callable) { if (callable == null) throw new NullPointerException(); this.callable = callable; this.state = NEW; // ensure visibility of callable } /** * Creates a {@code FutureTask} that will, upon running, execute the * given {@code Runnable}, and arrange that {@code get} will return the * given result on successful completion. * * @param runnable the runnable task * @param result the result to return on successful completion. If * you don't need a particular result, consider using * constructions of the form: * {@code Future<?> f = new FutureTask<Void>(runnable, null)} * @throws NullPointerException if the runnable is null */ public FutureTask(Runnable runnable, V result) { this.callable = Executors.callable(runnable, result); this.state = NEW; // ensure visibility of callable }
可以看到,Runnable注入会被Executors.callable()函数转换为Callable类型,即FutureTask最终都是执行Callable类型的任务。该适配函数的实现如下 :
/** * Returns a {@link Callable} object that, when * called, runs the given task and returns the given result. This * can be useful when applying methods requiring a * {@code Callable} to an otherwise resultless action. * @param task the task to run * @param result the result to return * @param <T> the type of the result * @return a callable object * @throws NullPointerException if task null */ public static <T> Callable<T> callable(Runnable task, T result) { if (task == null) throw new NullPointerException(); return new RunnableAdapter<T>(task, result); }
RunnableAdapter适配器
/** * A callable that runs given task and returns given result */ static final class RunnableAdapter<T> implements Callable<T> { final Runnable task; final T result; RunnableAdapter(Runnable task, T result) { this.task = task; this.result = result; } public T call() { task.run(); return result; } }
由于FutureTask实现了Runnable,因此它既可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行。并且还可以直接通过get()函数获取执行结果,该函数会阻塞,直到结果返回。
因此FutureTask既是Future、Runnable,又是包装了Callable(如果是Runnable最终也会被转换为Callable ), 它是这两者的合体。
完整示例:
package com.stay4it.rx; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; public class FutureTest { public static class Task implements Runnable { @Override public void run() { // TODO Auto-generated method stub System.out.println("run"); } } public static class Task2 implements Callable<Integer> { @Override public Integer call() throws Exception { System.out.println("call"); return fibc(30); } } /** * runnable, 无返回值 */ public static void testRunnable(){ ExecutorService executorService = Executors.newCachedThreadPool(); Future<String> future = (Future<String>) executorService.submit(new Task()); try { System.out.println(future.get()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } executorService.shutdown(); } /** * Callable, 有返回值 */ public static void testCallable(){ ExecutorService executorService = Executors.newCachedThreadPool(); Future<Integer> future = (Future<Integer>) executorService.submit(new Task2()); try { System.out.println(future.get()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } executorService.shutdown(); } /** * FutureTask则是一个RunnableFuture<V>,即实现了Runnbale又实现了Futrue<V>这两个接口, * 另外它还可以包装Runnable(实际上会转换为Callable)和Callable * <V>,所以一般来讲是一个符合体了,它可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行 * ,并且还可以通过v get()返回执行结果,在线程体没有执行完成的时候,主线程一直阻塞等待,执行完则直接返回结果。 */ public static void testFutureTask(){ ExecutorService executorService = Executors.newCachedThreadPool(); FutureTask<Integer> futureTask = new FutureTask<Integer>(new Task2()); executorService.submit(futureTask); try { System.out.println(futureTask.get()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } executorService.shutdown(); } /** * FutureTask则是一个RunnableFuture<V>,即实现了Runnbale又实现了Futrue<V>这两个接口, * 另外它还可以包装Runnable(实际上会转换为Callable)和Callable * <V>,所以一般来讲是一个符合体了,它可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行 * ,并且还可以通过v get()返回执行结果,在线程体没有执行完成的时候,主线程一直阻塞等待,执行完则直接返回结果。 */ public static void testFutureTask2(){ ExecutorService executorService = Executors.newCachedThreadPool(); FutureTask<Integer> futureTask = new FutureTask<Integer>(new Runnable() { @Override public void run() { // TODO Auto-generated method stub System.out.println("testFutureTask2 run"); } },fibc(30)); executorService.submit(futureTask); try { System.out.println(futureTask.get()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } executorService.shutdown(); } public static void main(String[] args) { testCallable(); } /** * 效率低下的斐波那契数列, 耗时的操作 * * @param num * @return */ static int fibc(int num) { if (num == 0) { return 0; } if (num == 1) { return 1; } return fibc(num - 1) + fibc(num - 2); } }
CompletionService
《Java并发编程实践》中关于CompletionService的描述如下:如果向Executor提交了一组计算任务,并且希望在计算完成后获得结果,那么可以保留与每个任务关联的Future,然后反复使用get方法,同时将参数timeout指定为0,从而通过轮询来判断任务是否完成。这种方法虽然可行,但却有些繁琐。幸运的是,还有一种更好的方法:完成服务CompletionService。
CompleteService接口是为了方便多个任务执行时,可以方便得获取到执行任务的Future结果。接口内容如下:
public interface CompletionService<V> { Future<V> submit(Callable<V> task); Future<V> submit(Runnable task, V result); Future<V> take() throws InterruptedException; Future<V> poll(); Future<V> poll(long timeout, TimeUnit unit) throws InterruptedException; }
这五个方法分为两大方面。一个是对Callable和Runnable类型参数的任务提交,另一方面则是尝试对结果以不同的方式进行获取,take()方法一般是阻塞式的获取,后两者则更灵活。
通常来讲,CompleteService是要和Executor结合在一起使用的。
ExecutorCompletionService
在JDK中,ExecutorCompletionService是CompletionService接口的唯一实现类。这个实现类主要做的事就是将执行完成的任务结果放到阻塞队列中,这样等待结果的线程,如果执行take()方法会得到结果并恢复执行。
ExecutorCompletionService有3个属性:
AbstractExecutorService类的对象aes
Executor类的对象executor
BlockingQueue<Future<V>>的completionQueue
通常,如果executor是AbstractExecutorService的一个实现,则将其赋值给aes属性,否则赋值为null。
在这个类中,executor负责执行任务,而aes则负责做适配处理,返回包装好任务的FutureTask对象。
这里面有一个对于实现功能很重要的内部类QueueingFuture,实现如下:
/** * FutureTask extension to enqueue upon completion */ private class QueueingFuture extends FutureTask<Void> { QueueingFuture(RunnableFuture<V> task) { super(task, null); this.task = task; } protected void done() { completionQueue.add(task); } private final Future<V> task; }
QueueingFuture是FutureTask的一个子类,通过扩展该子类的done方法,可以实现当任务完成时,将结果放入到BlockingQueue中。
而通过使用BlockingQueue的take或poll方法,则可以得到结果。在BlockingQueue不存在元素时,这两个操作会阻塞,一旦有结果加入,则立即返回。
public Future<V> take() throws InterruptedException { return completionQueue.take(); } public Future<V> poll() { return completionQueue.poll(); }
下面我们通过例子来体验下CompletionService的好处与使用场景。
首先定义一个实现了Callable接口的Task类:
private static class Task implements Callable<String>{ private volatile int i; public Task(int i){ this.i = i; } @Override public String call() throws Exception { Thread.sleep(1000); System.out.println(Thread.currentThread().getName()); return "任务 : " + i; } }
1)自己维护一个list保存submit的callable task所返回的Future对象。在主线程中遍历集合并调用Future的get()方法取到Task的返回值。如下代码所示:
public static void testFuture() throws InterruptedException, ExecutionException { System.out.println("main Thread begin:"); ExecutorService executor = Executors.newCachedThreadPool(); List<Future<String>> result = new ArrayList<Future<String>>(); for (int i = 0;i<10;i++) { Future<String> submit = executor.submit(new Task(i)); result.add(submit); } executor.shutdown(); for (int i = 0;i<10;i++) {//一个一个等待返回结果 System.out.println(result.get(i).get()); } System.out.println("main Thread end:"); }
输出结果如下:
main Thread begin: pool-1-thread-2 pool-1-thread-1 pool-1-thread-3 任务 : 0 任务 : 1 任务 : 2 pool-1-thread-10 pool-1-thread-6 pool-1-thread-9 pool-1-thread-8 pool-1-thread-7 pool-1-thread-4 pool-1-thread-5 任务 : 3 任务 : 4 任务 : 5 任务 : 6 任务 : 7 任务 : 8 任务 : 9 main Thread end:
从输出结果可以看出,我们只能一个一个阻塞的取出。这中间肯定会浪费一定的时间在等待上。如5返回了,但是前面的1-4都没有返回,那么5就得等1-4输出才能输出。
2)通过CompletionService包装ExecutorService,然后调用其take()方法去取Future对象。如下代码所示:
private static void testCompletionService() throws InterruptedException, ExecutionException { System.out.println("main Thread begin:"); ExecutorService executor = Executors.newCachedThreadPool(); ExecutorCompletionService<String> completionService = new ExecutorCompletionService<>(executor); for(int i=0;i<10;i++){ completionService.submit(new Task(i)); } executor.shutdown(); for(int i=0;i<10;i++){ System.out.println(completionService.take().get()); } System.out.println("main Thread end:"); }
输出结果如下:
main Thread begin: pool-1-thread-9 pool-1-thread-7 pool-1-thread-5 pool-1-thread-6 pool-1-thread-3 pool-1-thread-4 任务 : 8 任务 : 5 任务 : 4 任务 : 6 pool-1-thread-2 pool-1-thread-10 pool-1-thread-1 pool-1-thread-8 任务 : 2 任务 : 3 任务 : 1 任务 : 9 任务 : 0 任务 : 7 main Thread end:
可以看出,结果的输出和线程的放入顺序无关系。每一个线程执行成功后,立刻就输出。如5返回了,不管前面的1-4有没有返回,5马上输出,不管它们加入线程池的顺序,从而节省时间。
总结
自己创建一个集合来保存Future存根并循环调用其返回结果的时候,主线程并不能保证首先获得的是最先完成任务的线程返回值。它只是按加入线程池的顺序返回。因为take方法是阻塞方法,后面的任务完成了,前面的任务却没有完成,主程序就那样等待在那儿,只到前面的完成了,它才知道原来后面的也完成了。使用CompletionService来维护处理线程的返回结果时,主线程总是能够拿到最先完成的任务的返回值,而不管它们加入线程池的顺序。
CompletionService的实现是维护了一个保存Future的BlockingQueque。只有当这个Future的任务状态是结束的时候,才会加入到这个Queque中,take()方法其实就是Producer-Consumer中的Consumer。它会从Queue中取出Future对象,如果Queue是空的,就会阻塞在那里,直到有完成的Future对象加入到Queue中。也就是先完成的必定先被取出,这样就减少了不必要的等待时间。
相关文章推荐
- Java中的Runnable、Callable、Future、FutureTask的区别和CompletionService的使用场景
- Java中的Callable、Future、FutureTask、Runnable的区别与示例
- Java中的Runnable、Callable、Future、FutureTask的区别
- Java中的Runnable、Callable、Future、FutureTask的区别与示例
- Java中的Runnable、Callable、Future、FutureTask的区别与示例
- Java中的Runnable、Callable、Future、FutureTask的区别与示例
- Java中的Runnable、Callable、Future、FutureTask的区别与示例
- Java中的Runnable、Callable、Future、FutureTask的区别与示例
- Java中的Runnable、Callable、Future、FutureTask的区别与示例
- Java中的Runnable、Callable、Future、FutureTask的区别与示例
- Java中的Runnable、Callable、Future、FutureTask的区别与示例
- Java中的Runnable、Callable、Future、FutureTask的区别与示例
- Java中的Runnable、Callable、Future、FutureTask的区别与示例
- Java中的Runnable、Callable、Future、FutureTask的区别与示例
- Java中的Runnable、Callable、Future、FutureTask的区别与示例
- 0100 Java中的Runnable、Callable、Future、FutureTask的区别与示例【进阶】
- Java中的Runnable、Callable、Future、FutureTask的区别
- Java中的Runnable、Callable、Future、FutureTask的区别与示例
- Java中的Runnable、Callable、Future、FutureTask的区别与示例
- Java中的Runnable、Callable、Future、FutureTask的区别与示例