ThreadPoolExecutorService 按顺序而不是并发执行线程?

ThreadPoolExecutorService executing threads sequentially instead of concurrently?

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

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

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

相反,创建了一个新线程,但只有当它完成时,我的主机线程才会再次继续。

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

如何使用执行程序服务执行此操作?

我目前正在初始化如下:

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, 加尔