【问题标题】:get a single Thread from ThreadPoolExecutor从 ThreadPoolExecutor 获取单个线程
【发布时间】:2013-01-23 01:57:08
【问题描述】:

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

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

剩下的代码......

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

【问题讨论】:

    标签: java multithreading pool executor threadpoolexecutor


    【解决方案1】:

    是的,您可以submit,在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() 挂起当前线程的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      相关资源
      最近更新 更多