我正在运行一个带有许多线程的ThreadPoolExecutor。 我想操纵线程中的一些数据,所以我想发送一个对象 线程和完成后使用数据。 我知道如何等待线程完成join()的唯一方法 然后使用数据。 问题是,我无法从ThreadPoolExecutor获得单个线程。 我想做这样的事情:
Thread t = ThreadPoolExecutor.getThread();
t.start();
t.join();
其余代码......
有没有人有办法? 我知道我可以使用Callable,但我想避免这种情况,因为我已经有了预先存在的代码......
答案 0 :(得分:4)
是的,submit
Future
,get()
返回Future
和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()
挂起当前线程,类似于{{1}}挂起当前线程的方式。