如何从父线程中使用的线程中获取值?

时间:2018-06-07 02:59:16

标签: java multithreading

final Boolean result;
new Thread(() -> {
result = new DaoToUserInfo("porebook").queryUser(user);
}).start();

这是一个例子。queryUser(User user)返回一个布尔值。如何将此值赋给外部变量result(我知道无法更改不可变数据类型)或如何从外部范围获取此值?

1 个答案:

答案 0 :(得分:1)

//This is example, you may have to adjust your code , what type of pool you need. etc.
ExecutorService ex = Executors.newSingleThreadPoolExecutor();
Future<Boolean> f = ex.submit(() -> return new DaoToUserInfo("porebook").queryUser(user));
final boolean result = f.get(); //this will block until result is available