guava 併發

概念

        ListenableFuture顧名思義就是能夠監聽的Future,它是對java原生Future的擴展加強。咱們知道Future表示一個異步計算任務,當任務完成時能夠獲得計算結果。若是咱們但願一旦計算完成就拿到結果展現給用戶或者作另外的計算,就必須使用另外一個線程不斷的查詢計算狀態。這樣作,代碼複雜,並且效率低下。使用ListenableFuture Guava幫咱們檢測Future是否完成了,若是完成就自動調用回調函數,這樣能夠減小併發程序的複雜度。java

代碼:併發

import com.google.common.util.concurrent.*;
import java.util.concurrent.*;
/**
 * Created by admin on 2016/4/27.
 */
public class ExcutorEngineTest {
    public static void main(String[] args) throws Exception {
        ListeningExecutorService executorService = MoreExecutors
            .listeningDecorator(MoreExecutors
                .getExitingExecutorService(new ThreadPoolExecutor(10, 100,
                    3000, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>())));
        ListenableFuture<Integer> future = executorService.submit(new Task("test"));
        System.out.println("future:" + future.get());
        Futures.addCallback(future, new FutureCallback<Integer>() {
            @Override
            public void onSuccess(Integer result) {
                System.out.println("result" + result);
            }
            @Override
            public void onFailure(Throwable t) {
                System.err.println("error");
            }
        });
    }
    static class Task implements Callable<Integer>{
        String str;
        public Task(String str){
            this.str = str;
        }
        @Override
        public Integer call() throws Exception {
            System.out.println("call excute...." + str);
            return 8;
        }
    }
}

--------------------異步

執行結果:ide

call excute....test函數

future:8this

result8google

相關文章
相關標籤/搜索