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();