zoukankan      html  css  js  c++  java
  • Java并发入门之FutureTask

    Java并发入门之FutureTask

    前言:

    最近遇到一个项目需要上传图片到服务器,API要求是二进制流,那就跑慢点一点点上传。

    于是对多线程从没有应用过的我,决定拿多线程直接应用于代码。

    应用Executors框架:

    ExecutorService threadPool = Executors.newFixedThreadPool(10);
            Map<Integer,Future<String>> futuresMap = new HashMap<>();
            for(final OurGoods goods : ourGoodsList){
                Future<String> future = threadPool.submit(new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        return processImage(goods,xxxxode,sysParam);
                    }
                });
                futuresMap.put(goods.getGoodsId(),future);
            }

    提交到一个结果集后进行判断

    暂时这么写,比较Low但是还算比较规范的写法。。

     for(Integer goodsId : batchFutureMap.keySet()){
    	String image;
        try {
        	Future imageTask = batchFutureMap.get(goodsId);
        	boolean successed = true;
        	while(!imageTask.isDone()){
        		try {
        			Thread.sleep(10);//sleep for 10 millisecond before checking again
        		} catch (InterruptedException e) {
        			successed = false;
        			e.printStackTrace();
        		}
        	}
        	if(!successed){
        		continue;
        	}
        	image = imageTask.get();
        	if(image != null){
        		imageMap.put(goodsId,image);
        	}
        }
        catch (InterruptedException | ExecutionException e) {
        	e.printStackTrace();
        }
    }
    

    别忘了关闭线程池,如果不再使用的话:

    threadPool.shutdown();


  • 相关阅读:
    线性代数思维导图——3.向量
    微分中值定理的基础题型总结
    构造函数
    Python课程笔记(七)
    0241. Different Ways to Add Parentheses (M)
    0014. Longest Common Prefix (E)
    0013. Roman to Integer (E)
    0011. Container With Most Water (M)
    0010. Regular Expression Matching (H)
    0012. Integer to Roman (M)
  • 原文地址:https://www.cnblogs.com/slankka/p/9158505.html
Copyright © 2011-2022 走看看