java - 从 ThreadPoolExecutor 获取单个线程

标签 java multithreading pool executor threadpoolexecutor

我正在运行一个带有多个线程的 ThreadPoolExecutor。 我想操作线程中的一些数据,所以我想发送一个对象到 线程完成后使用数据。 我知道的唯一方法是等待线程完成 join() 然后使用数据。 问题是,我无法从 ThreadPoolExecutor 获取单个线程。 我想做这样的事情:

Thread t = ThreadPoolExecutor.getThread();
t.start();
t.join();

其余代码......

有人有办法吗? 我知道我可以使用 Callable 但我想避免这种情况,因为我已经有预先存在的代码...

最佳答案

是的,您可以提交,获取Future返回并在Futureget()

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/

相关文章:

java - 我的命令 javac 没有显示任何结果

java - 为什么这个 GridBagLayout 有未使用的空白空间,我该如何摆脱它?

c++ - 程序关闭时 notify_all() 崩溃

python - Python 中池的使用

python - 并行处理 - 池 - Python

c++ - 一个大池还是几个特定类型的池?

java - 虫洞攻击实现-传感器

java - 使用 Java 检测编码

python - 如何从Python中的多个线程收集数据?

C Linux pthreads : sending data from one thread to antoher using message queue gives unexpected result