所以我试图从一个线程中启动一个新线程。



function(update):
  under certain conditions:
    add a new thread running same service as current


理想情况下,我希望新线程运行,而我当前的线程继续执行。

而是创建了一个新线程,但只有在完成后,我的宿主线程才会再次继续。

理想情况下,我需要它并发执行,在其中添加新线程与从我的原始类添加线程具有相同的效果。

我如何使用执行器服务来做到这一点?

我目前正在初始化,如下所示:

ExecutorService executorService = Executors.newFixedThreadPool(100);


添加线程功能:

 final SimulatedAnnealingCallable simulatedAnnealingCallable =
            new SimulatedAnnealingCallable(this, schedule);

 final Future<Schedule> future = executorService.submit(simulatedAnnealingCallable);

try {
        future.get();
    } catch (ExecutionException ex) {
        ex.getCause().printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }


关机稍后发生

最佳答案

原因是您在future.get()中阻塞了主线程。

实际发生的情况是,您的主线程与执行程序一起启动了新的未来任务,然后您通过告诉主线程等待执行任务的结果来阻塞主线程。

解决此问题的一种方法是不等待将来完成,而是添加功能以使您可以使用callable知道任务已完成。

例如

public interface CompletedTask {
  void completed(boolean succes);
}

// change SimulatedAnnealingCallable to receive CompletedTask in constructor
// and call the instanc's completed method

public LogicClass implements CompletedTask {

  private void someFunc() {
    final SimulatedAnnealingCallable simulatedAnnealingCallable =
            new SimulatedAnnealingCallable(this, schedule);
    executorService.submit(simulatedAnnealingCallable);
  }

  public void completed(boolean succes) {
    System.out.println("task is completed with " + success);
  }
}


HTH,
加尔

10-07 19:01
查看更多