Guava 并发编程体验

大致解说一下 ,平时用到的JCU 包里的Future 中的get 方法会阻塞 而且不一定get的时候线程就执行完了,要人工去处理 比较麻烦。

接下来要说的就是Guava 中的 FutureCallback 、ListeningExecutorServiceListenableFuture   他们可以让线程池中的每一个线程执行完毕后去调用我们指定的方法 (由 FutureCallback  这个类处理)  我这边主要是写了一个int 值的相加 下面上代码 简单易懂。

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

import com.google.common.util.concurrent.*;

import java.util.concurrent.*;

/**
 * @Autohor MrZhong
 * @Description:
 **/
public class ThreadTest {

    private static int num = 0;

    private static StringBuilder builder = new StringBuilder();

    public static void main(String[] args) throws InterruptedException {
        //定义Callback
        FutureCallback<Integer> integerFutureCallback = new FutureCallback<Integer>() {
            @Override/*线程池执行结果对象 以下是integer*/
            public void onSuccess(Integer integer) {
                System.out.println("数值为:" + integer);
                num += integer;
                System.out.println("最终值为"+num);
            }
            @Override/*异常*/
            public void onFailure(Throwable throwable) {
                System.out.println(throwable.toString());
            }
        };
        //ExecutorService 线程池 转换为 ListeningExecutorService
        ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
        //创建 listenFutureCallback
        ListenableFuture<Integer> integerListenableFuture = null;

        long st= System.currentTimeMillis();

        for (int i = 1; i <= 10; i++) {
            int finalI = i;
            integerListenableFuture = listeningExecutorService.submit(() -> {
                return Integer.valueOf(1 + finalI);
            });
            Futures.addCallback(integerListenableFuture,integerFutureCallback);
        }

        System.out.println("开始关闭线程池……");

        listeningExecutorService.shutdownNow();

        System.out.println("线程池关闭中……");

        System.out.println("线程池状态:" + listeningExecutorService.isShutdown() + listeningExecutorService.isTerminated());

        try {
            System.out.println("最终数据" + integerListenableFuture.get());
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("耗时:"+(System.currentTimeMillis()-st));
    }

}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值