例子:
try {
List<Map<String, Object>> resList = new ArrayList<Map<String, Object>>();
// 创建线程池:当前可用数就可以了;多了也没用,cpu执行不过来还是会在等待;
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
// 各个线程的结果
List<Future<Boolean>> threadList = new ArrayList<Future<Boolean>>();
List<String> ids = new ArrayList<String>();
for (final String id : ids) {
// 为了提高效率,这里使用多线程对数据库操作
Future<Boolean> task = executor.submit(new Callable<Boolean>() {
public Boolean call() throws Exception {
boolean res = false;
try {
res = sendMsgById(id);
} catch (Exception e) {
logger.info("发送消息:线程出现异常");
}
return res;// 返回的是线程结果,不是方法结果
}
});
threadList.add(task);// 将线程放进list
}
// 获取所有线程的结果
for (Future<Boolean> future : threadList) {
// 线程返回的结果,此处可以把线程阻塞;
Boolean threadRes = future.get();
// 线程完成,继续下面判断;
if (!threadRes) {// 失败的线程
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("result", "error");
resultMap.put("message", "查询出现失败的线程,请联系IT处理");
}
}
// 获取所有线程的结果结束:因为future.get()会阻塞主线程;所以只有所有子线程结束后才会继续往下走
// 走到这里就已经得到所有的线程结束//
}catch(Exception e){
}finally{
executor.shutdown();
}