Java 多线程 线程池处理Callable请求

Callable请求有返回值,而Runnable请求没有返回值

可以利用Future接收返回值

继承Callable的执行类:

class GetUserInfo implements Callable{

    private String id;
    GetUserInfo(String id){
        this.id = id;
    }

    @Override
    public Object call() throws Exception {
        UserInfo userInfo =getUserInfoById(id);
        return userInfo;
    }
}

利用Future接收

List<String> idList = getIdList();
List<Future<UserInfo>> futures = Lists.newArrayList();
List<UserInfo> userInfos = new ArrayList<UserInfo>();
for (String id : idList){
    Future<UserInfo> futureUserInfo = threadPool.submit(new GetUserInfo(id));
    futures.add(futureUserInfo);
}

futures.forEach(eachFuture -> {
    try {
        userInfos.add(eachFuture.get());
    } catch (Exception e) {
        e.printStackTrace();
    }
});

你可能感兴趣的:(Java)