本文主要是介绍ListenableFuture和countdownlatch使用example,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
ListenableFuture可以允许你注册回调方法(callbacks),在运算(多线程执行)完成的时候进行调用, 或者在运算(多线程执行)完成后立即执行
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>() {@Overridepublic 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);}@Overridepublic void onFailure(Throwable t) {System.out.println("error" + t.getMessage());}}, MoreExecutors.directExecutor());Futures.addCallback(listenableFuture2, new FutureCallback<String>() {@Overridepublic 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);}@Overridepublic 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();}
}
这篇关于ListenableFuture和countdownlatch使用example的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!