java中有几种实现异步的方式(FutureTask/ListenableFuture/CompletableFuture)
这篇介绍的是FutureTask
class Worker {
public String name;
Worker(String name) {
this.name = name;
}
}
/**
* @author dong
*/
public class FutureTaskTest {
public static FutureTask<Worker> addWorker(String name) {
FutureTask<Worker> futureTask = new FutureTask<>(() -> {
System.out.println(name + " do something");
Thread.sleep(1000);
return new Worker(name);
});
new Thread(futureTask).start();
return futureTask;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
List<FutureTask<Worker>> listTask = new ArrayList<>();
listTask.add(addWorker("东1"));
listTask.add(addWorker("东2"));
listTask.add(addWorker("东3"));
for(FutureTask<Worker> futureTask : listTask){
Worker worker = futureTask.get();
System.out.println("返回值:" + worker.name);
}
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start));
}
}
上面就是简单的使用FutureTask的异步调用
每个任务创建一个FutureTask,然后使用get去等待结果
说一下原理:
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
这个是FutureTask的构造函数,接收的是一个Callable,和Runnable的区别在于一个有返回值,一个没有
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}
构造完FutureTask之后就利用Thread创建一个子线程去处理任务
然后看一下FutureTask的继承关系
发现其实实现了Runnable接口,所以子线程会去执行run方法
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
主要就是执行Callable的call方法(实际上就是你要执行的任务方法)
然后会得到一个结果result,最后传入set方法
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
这里主要就是把结果v赋值给outcome(成员变量),因为这个结果将来会在get的时候才被取出来
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
如果沒有完成任务,就等待
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
for (;;) {
if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
else if (q == null)
q = new WaitNode();
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else
LockSupport.park(this);
}
}
如果已经完成任务
private V report(int s) throws ExecutionException {
Object x = outcome;
if (s == NORMAL)
return (V)x;
if (s >= CANCELLED)
throw new CancellationException();
throw new ExecutionException((Throwable)x);
}