/* 业务逻辑处理 */ public class ATask implements Callable<Map<String, Object>> { private Map<String, Object> aMap; public ATask(Map<String, Object> aMap) { this.aMap = aMap; } public Map<String, Object> call() throws Exception { Map<String, Object> resultMap = new HashMap<String, Object>(); String taskFlag = "0";// 0-无返回;1-返回成功;2-返回失败;3-其他异常 String taskMsg = ""; //业务逻辑 resultMap.put('taskFlag',taskFlag); resultMap.put('taskMsg',taskMsg); return resultMap; } }
/*
创建线程池,传入处理内容
*/
public class AThread implements Runnable {
public void run() {
// 创建线程池
ExecutorService pools = Executors.newFixedThreadPool(5);//5个线程
CompletionService<Map<String, Object>> completionService = new ExecutorCompletionService<Map<String, Object>>(pools);
Map<String, Object> aMap = new HashMap<String, Object>();
completionService.submit(new ATask(aMap));
Future<Map<String, Object>> f = completionService.take();// 如果完成队列中没有数据,则阻塞;否则返回队列中的数据
Map<String, Object> taskResult = f.get();
taskResult.get("taskFlag");
taskResult.get("taskMsg");
// 关闭线程池
pools.shutdown();
}
}
/*
最外层进行启动线程
*/
AThread aThread = new AThread();
Thread thread=new Thread(aThread);
thread.start();