线程返回值问题

平时我们写Java程序或者是Android程序的时候有这样一个问题,耗时操作我们需要写到线程里面去,但是一旦写到线程里面去,我们又会发现很难获得返回值,当然天无绝人之路 我们可以通过 EventBus框架传值过去,也可以通过Handle传值过去,同样也可以自己写回调接口。


今天我教大家一个直接调用方法获取线程里面的耗时操作方法

1,首先我们可以准好好耗时操作

**
 * 
 * 线程返回一个List数据,在这里这个类没有run()方法,但是我们可以把它看成一个线程
 *
 */
public class QueryDataThread implements Callable<List<Map<String,Object>>>{

    private Map<String,Object> param = null ;

    public QueryDataThread(Map<String,Object> param){
        super();
        this.param = param;
    }


    public List call() throws Exception {
          /* 模拟查询DB后得到结果集合 */
        System.out.println("param -> " + param);
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("id", "1001");
        map1.put("name", "nick huang");

        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("id", "1002");
        map2.put("name", "darren lin");
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        list.add(map1);
        list.add(map2);
        /* 设置短暂的睡眠以便观察效果 */
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return list;
    }

}

怎么用呢,我们在新建一个Test类

        // 因为需要一个Map集合,所以这里创建一个我们传进去
         Map<String,Object> myMap = new HashMap<>();
        // 创建一个ExecutorService 的实例,从后面的名字我们可以理解为缓冲线程池
          ExecutorService  exectorExecutorService =  
          Executors.newCachedThreadPool();
          QueryDataThread  queryDataThread = new QueryDataThread(myMap);
          //下面就是比较关键的代码 我们可以理解位开启线程之后
        /** 这里是submit的源码介绍,开启了一个Runnable,返回一个Future
     * Submits a Runnable task for execution and returns a Future
     * representing that task. The Future's {@code get} method will
     * return {@code null} upon <em>successful</em> completion.
     *
     * @param task the task to submit
     * @return a Future representing pending completion of the task
     * @throws RejectedExecutionException if the task cannot be
     *         scheduled for execution
     * @throws NullPointerException if the task is null
     */
    Future<?> submit(Runnable task);
          Future<List<Map<String, Object>>> resultFuture =         
          exectorExecutorService.submit(queryDataThread);
          System.out.println("size==="+resultFuture.get().size());
          System.out.println("size==="+resultFuture.get().get(0).get("name"));
//返回的情况位
param -> {}
size===2
size===nick huang
posted @   飞航之梦  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示