我正在运行一个带有多个线程的 ThreadPoolExecutor。 我想操作线程中的一些数据,所以我想发送一个对象到 线程完成后使用数据。 我知道的唯一方法是等待线程完成 join() 然后使用数据。 问题是,我无法从 ThreadPoolExecutor 获取单个线程。 我想做这样的事情:
Thread t = ThreadPoolExecutor.getThread();
t.start();
t.join();
其余代码......
有人有办法吗? 我知道我可以使用 Callable 但我想避免这种情况,因为我已经有预先存在的代码...
最佳答案
是的,您可以提交
,获取Future
返回并在Future
上get()
Future<SomeResult> future = executorService.submit(new Callable<SomeResult>(){
public SomeResult call(){
//do work
return new SomeResult();
}
});
future.get();//suspends the current thread until the SomeResult callable returns.
基本上,call()
调用是在池中的线程之一上完成的,get()
会暂停当前线程,类似于 t .join()
挂起当前线程。
关于java - 从 ThreadPoolExecutor 获取单个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14753298/