Java-线程池的异步运行和同步返回

ExecutorService是Java中封装好的线程池类,可以定义线程池的数量,已经实现异步结果的同步返回。

int taskSize = reqList.size();
ExecutorService pool = Executors.newFixedThreadPool(taskSize);
List<Future> list = new ArrayList<Future>();
for (int i = 0; i < taskSize; ++i) {
    Callable c = new CustomCallable();
    Future f = pool.submit(c);
    list.add(f);
}
pool.shutdown();
for (Future f : list) {
    System.out.println(f.get());
}

其中,CustomCallable类需要实现以下接口:

Callable<Object>

举例:

class CustomCallable implements Callable<Object>{

    @Override
    public Object call() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }
}