ListenableFuture异步多线程代码实现

      本文以多次查询数据库为例进行说明。为了能够模拟查询数据库,这里会事先创建一个map,将查询条件和查询结果封装到map中。 
          在batchExec方法中,传入带有泛型的查询条件集合,核心操作是遍历查询条件集合,将每一个查询条件传给SingleTask(业务实现类),SingleTask必需要实现callable接口,在call方法中实现查询业务,这里使用上面创建好的map来进行模拟操作。 
          对于每一个查询任务SingleTask,将其放入ListeningExecutorService的submit()方法中执行,会返回一个ListenableFuture对象,我们使用Futures的addCallback()方法对得到的ListenableFuture进行监听,如果success则得到查询结果,并将结果放入结果集合中。这里需要注意的是需要将每一个ListenableFuture单独存入一个集合中,使用Futures的allAsList()方法能够得到一个新的ListenableFuture对象,然后使用future的get()方法来阻塞这个ListenableFuture。这么做的原因是:必须等到所有的查询结果都返回后,才能返回最终的查询结果。

2.1 装饰者模式获得ListeningExecutorService。

2.2 ListenableFuture listenableFuture = pool.submit()获得 ListenableFuture。

2.3 Futures.addCallback()设置回调函数。

 

package com.uitl.TaskUtil;

import com.google.common.util.concurrent.*;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;

 

public class MutiFutureTask {
    private static final int PoolSize = 20;

    //带有回调机制的线程池
    private static final ListeningExecutorService pool= MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(PoolSize));
    public static <T, V> List<V> batchExec(List<T> params, BatchFuture<T, V> batchFuture) {
        if(CollectionUtils.isEmpty(params)){
            return null;
        }
        final List<V> value = Collections.synchronizedList(new ArrayList<V>());
        try{
            List<ListenableFuture<V>> futures = new ArrayList<ListenableFuture<V>>();
            for(T t : params){
                //将实现了Callable的任务提交到线程池中,得到一个带有回调机制的ListenableFuture实例
                ListenableFuture<V> sfuture = pool.submit(new SingleTask<T, V>(t, batchFuture));
                Futures.addCallback(sfuture, new FutureCallback<V>() {
                    @Override
                    public void onSuccess(V result) {
                        value.add(result);
                    }
                    @Override
                    public void onFailure(Throwable t) {
                        throw new RuntimeException(t);
                    }
                });
                futures.add(sfuture);
            }
            ListenableFuture<List<V>> allAsList = Futures.allAsList(futures);
            allAsList.get();
        }catch(InterruptedException e){
            e.printStackTrace();
        }catch(ExecutionException e){
            e.printStackTrace();
        }

        return value;
    }

    /**
     *业务实现类
     * @param <T>
     * @param <V>
     */

    private static class SingleTask<T, V> implements Callable<V> {
        private T param;
        private BatchFuture<T, V> batchFuture;
        public SingleTask(T param, BatchFuture<T, V> batchFuture){
            this.param = param;
            this.batchFuture = batchFuture;
        }

        @Override
        public V call() throws Exception {
            return batchFuture.callback(param);
        }
    }
    public interface BatchFuture<T,V>{
        V callback(T param);
    }
}
class MutiFutureTaskTest {

    private static final Map<Integer,Person> persons = new HashMap<Integer,Person>();
    static{
        persons.put(1, new Person(1, "test1", 1, "aaa", 8888888888l));
        persons.put(2, new Person(2, "test2", 2, "bbb", 8888888888l));
    }

    public static void main(String[] args) {
        List<Integer> param = new ArrayList<Integer>();
        param.add(1);
        param.add(2);
        param.add(3);
        param.add(4);
        param.add(5);
        List<Person> result = MutiFutureTask.batchExec(param, new MutiFutureTask.BatchFuture<Integer, Person>() {
            @Override
            public Person callback(Integer param) {
                return persons.get(param);
            }
        });
        System.out.println(result.size());
    }
}转自 : https://blog.csdn.net/pistolove/article/details/53389646 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值