Callable與Future
使用線程池來創建並行的任務:
這個一個簡單的demo,可以在最後統一獲取執行結果;以此類推
方案一:
ExecutorService threadPool = Executors.newFixedThreadPool(2);
Future<Integer> future = threadPool.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return 1;
}
});
Future<Integer> futureNew = threadPool.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return 2;
}
});
try {
System.out.println(future.get());
System.out.println(futureNew.get());
} catch (Exception e) {
e.printStackTrace();
}
企業應用:
public static void main(String[] args) throws ParseException {
try{
ThreadPoolExecutor threadPool = ImportDataThreadPoolUtil.getInstance();
FutureTask<Boolean> futureTask = new FutureTask(new Callable() {
public Boolean call() throws Exception {
//do something
return null;
}
});
threadPool.execute(futureTask);
Boolean flag = false;
Long userTime = 0L;
while (userTime < 10) {
flag = futureTask.get();
if (futureTask.isDone() ) {
break;
}
Thread.sleep(500);//線程鎖定
userTime++;
}
}catch (Exception e){
System.out.println("error ~~");
}
}