ListenableFuture可以允许你注册回调方法(callbacks),在运算(多线程执行)完成的时候进行调用, 或者在运算(多线程执行)完成后立即执行文章来源地址https://www.toymoban.com/news/detail-732224.html
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();
}
}
文章来源:https://www.toymoban.com/news/detail-732224.html
到了这里,关于ListenableFuture和countdownlatch使用example的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!