以下SSCCE显示从服务器(例如)获取记录。ExecutorService
用于创建ThreadPool
2 个线程,我用Timeout
3 秒调用了所有这些线程。我故意让一些任务失败。
现在我的问题是,如何获取失败任务的 EmpID?
主类:
public class MultiThreadEx {
public static void main(String[] args) {
String[] empIDArray = {
"100", "200", "300", "400", "500",
"600", "700", "800", "900", "1000",
"1100", "1200", "1300", "1400", "1500"
};
List<ThreadTaskEach> taskList = new ArrayList<ThreadTaskEach>();
try {
for(String empID : empIDArray) {
taskList.add(new ThreadTaskEach(empID));
}
} catch(Exception e) {
System.out.println("Exception occured: " + e.getMessage());
}
List<Future<Map<String, String>>> futureList = null;
try {
ExecutorService service = Executors.newFixedThreadPool(2);
futureList = service.invokeAll(taskList, 3, TimeUnit.SECONDS);
service.shutdown();
} catch(InterruptedException ie) {
System.out.println("Exception occured: " + ie.getMessage());
}
for(Future<Map<String, String>> future : futureList) {
try {
Map<String, String> resultMap = future.get();
for(String key : resultMap.keySet()) {
System.out.println(resultMap.get(key));
}
} catch(ExecutionException ee) {
System.out.println("Exception occured: " + ee.getMessage());
} catch (InterruptedException ie) {
System.out.println("Exception occured: " + ie.getMessage());
} catch(CancellationException e) {
System.out.println("Exception occured: " + e.getMessage());
}
}
}
}
线程类
class ThreadTaskEach implements Callable<Map<String, String>>{
private String empID;
public ThreadTaskEach(String empID) {
this.empID = empID;
}
@Override
public Map<String, String> call() throws Exception {
try {
return prepareMap(empID);
} catch(Exception e) {
System.out.println("Exception occured: " + e.getMessage());
throw new Exception("Exception occured: " + e.getMessage());
}
}
private Map<String, String> prepareMap(String empID) throws InterruptedException {
Map<String, String> map = new HashMap<String, String>();
if(Integer.parseInt(empID) % 500 == 0) {
Thread.sleep(5000);
}
map.put(empID, empID + ": " + Thread.currentThread().getId());
return map;
}
}
在上面的代码 500, 1000 .. 未能在 3 秒内完成。
Map<String, String> resultMap = future.get();
因此,当我为这些任务说 future.get() 时,我得到了CancellationException
. 但是如何从任务中获取 EmpID 呢?