ListenableFuture可以允许你注册回调方法(callbacks),在运算(多线程执行)完成的时候进行调用, 或者在运算(多线程执行)完成后立即执行
java
import com.google.common.util.concurrent.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* 如果需要所有的listenableFuture返回结果,可以使用countdownlatch,在Futures.addCallback的success里面把countdownlatch减1
* 等countdownlatch=0的时候,所有的listenableFuture都计算完成
*/
public class ListenableFutureLearn2 {
public void test3() throws Exception {
ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
// 执行任务
final ListenableFuture<String> listenableFuture = executorService.submit(new Callable<String>() {
public String call() throws Exception {
for (int i = 0; i < 10000; i++) {
System.out.println(i);
}
return "success";
}
});
final ListenableFuture<String> listenableFuture2 = executorService.submit(new Callable<String>() {
public String call() throws Exception {
for (int i = 0; i < 10000; i++) {
System.out.println(-i);
}
return "success";
}
});
// 绑定任务以及回调函数
Futures.addCallback(listenableFuture, new FutureCallback<String>() {
@Override
public void onSuccess(String result) {
String str = "";
try {
str = listenableFuture.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("integer:" + str);
System.out.println("result:" + result);
}
@Override
public void onFailure(Throwable t) {
System.out.println("error" + t.getMessage());
}
}
, MoreExecutors.directExecutor());
Futures.addCallback(listenableFuture2, new FutureCallback<String>() {
@Override
public void onSuccess(String result) {
String str = "";
try {
str = listenableFuture.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("integer:" + str);
System.out.println("result:" + result);
}
@Override
public void onFailure(Throwable t) {
System.out.println("error" + t.getMessage());
}
}
, MoreExecutors.directExecutor());
TimeUnit.MILLISECONDS.sleep(500);
System.out.println("listenableFuture:" + listenableFuture.get());
}
public static void main(String[] args) throws Exception {
new ListenableFutureLearn2().test3();
}
}