簡體   English   中英

ThreadPoolExecutorService順序執行線程而不是並發執行嗎?

[英]ThreadPoolExecutorService executing threads sequentially instead of concurrently?

所以我試圖從一個線程中啟動一個新線程。

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,Gal

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM