Java ThreadPoolExecutorService按顺序而不是并发执行线程?
因此,我试图从一个线程中启动一个新线程 i、 e 理想情况下,我希望运行新线程,继续执行当前线程 相反,会创建一个新线程,但只有当它完成后,我的主机线程才会再次继续 理想情况下,我需要它并发执行,其中添加一个新线程与从我的原始类添加一个线程具有相同的效果 我如何使用executor service实现这一点 我目前正在进行如下初始化:Java ThreadPoolExecutorService按顺序而不是并发执行线程?,java,multithreading,executorservice,threadpoolexecutor,executor,Java,Multithreading,Executorservice,Threadpoolexecutor,Executor,因此,我试图从一个线程中启动一个新线程 i、 e 理想情况下,我希望运行新线程,继续执行当前线程 相反,会创建一个新线程,但只有当它完成后,我的主机线程才会再次继续 理想情况下,我需要它并发执行,其中添加一个新线程与从我的原始类添加一个线程具有相同的效果 我如何使用executor service实现这一点 我目前正在进行如下初始化: ExecutorService executorService = Executors.newFixedThreadPool(100); 添加线程函数: fi
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();
}
关机会在稍后发生原因是您将在将来阻塞主线程。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);
}
}
嗯,,
Gal请展示您是如何使用该服务的,现在就更新!那么猜你是在打电话给未来,所以你的第一个线程会阻塞,直到新线程完成?请添加一个更完整的示例,我们不必猜测。对不起,是的。。。假设这是clearCheck out CompletableFuture,它会为您提供更好的工具来处理此问题。我意识到,我在问如何避免这种情况,并让我的线程继续执行..修改了我的答案
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);
}
}