1、简介
1)2种创建线程方式:
继承Thread类和实现Runnable接口,执行完任务之后无法直接获取执行结果。
2)java 1.5开始,java.util.concurrent包中提供了Callable和Future,可以在任务执行完毕后得到任务的执行结果
3)实现Callable、Runnable接口的类,都是可以被其它线程执行的任务
2,Callable
1)Callable
is similar to java.lang.Runnable:A task that returns a result and may throw an exception
image.png
2)在线程池中的使用
提交任务到线程池,返回Future对象
image.png
image.png
线程池将Callable/Runable封装成FutureTask
image.png
3,Future
1)代表一个异步计算的结果
represents the result of an asynchronous computation.
Future<V>是一个泛型接口,V代表future执行的任务返回值类型。
image.png
2)接口中定义的方法
V get();Waits if necessary for the computation to complete, and then retrieves its result. 等待计算的完成,并取回结果。
V get(long timeout, TimeUnit unit);Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.最大等待timeout时长,然后如果可以获取的话,就取回结果,超时则抛出TimeoutException。
boolean isDone();Returns true if this task completed.
boolean isCancelled();Returns true if this task was cancelled before it completed normally.
boolean cancel(boolean mayInterruptIfRunning);Attempts to cancel execution of this task. 参数代表whether this task should be interrupted
3)Future接口常用的实现类
public interface RunnableFuture<V> extends Runnable, Future<V>接口继承了Runnable和Future接口。
public class FutureTask<V> implements RunnableFuture<V>A cancellable asynchronous computation. FutureTask can be used to wrap a Runnable object. A FutureTask can be submitted to an Executor.
4)FutureTask中有私有成员。can be used to wrap a Callable object
private Callable<V> callable;image.png
4,FutureTask内部实现
1)实现了Runnable和Future接口
是一个可让线程执行的任务;是一个可以获取Callable返回值的Future
image.png
2)FutureTask的run方法实现
底层调用Callable的call方法,使用cas+volatile设置任务的状态
image.png
image.png
image.png
3)FutureTask底层get方法实现
awaitDone底层调用LockSupport的park/parkNanos方法对主线程进行阻塞,cas+volatile将等待线程放入waiters列表
image.png
4)任务执行完毕底层实现
遍历waiters列表,unpark依次解除get方法放入waiters中线程的阻塞状态。
image.png
image.png












