簡體   English   中英

Java等待所有線程完成

[英]Java Waiting for all threads to complete

編輯:我的問題是不同的,它與鏈接的問題無關。

我正在用完成處理程序跟蹤代碼。

FutureTask<Void> futureTask = new FutureTask<Void>(() -> {
    System.out.println("callback");
    return null;
});

Runnable task = () -> {
    for(int i=0; i<5; i++) {
        System.out.println(Thread.currentThread().getName() + " " + i);
    }
    futureTask.run();
};

new Thread(task).start();
new Thread(task).start();

基本上,我正在尋找可變數量任務的完成處理程序,還是有另一種方法?

我從這個答案中得到啟發,但是當我在尋找本機解決方案時,它似乎是某些庫的一部分。

可完成的未來

這是我嘗試使用最終結果處理程序完成的期貨。

public void test() {
    CompletableFuture
            .supplyAsync(() -> method1())
            .supplyAsync(() -> method2())
            .supplyAsync(() -> result());
}

public String method1() {
    System.out.println("calling 1");
    return "method1";
}

public String method2() {
    System.out.println("calling 2");
    return "method2";
}

public String result() {
    System.out.println("result");
    return "result";
}

假設您的方法result()返回要檢索的值,即像Type result()那樣聲明,則可以使用

CompletableFuture<Type> f = CompletableFuture.allOf(
    CompletableFuture.runAsync(() -> method1()),
    CompletableFuture.runAsync(() -> method2())
).thenApply(_void -> result());

每個runAsync創建一個單獨的異步CompletableFuture ,一旦執行了Runnable ,該異步CompletableFuture將完成。 除了不返回結果外,它與supplyAsync相同。

allOf創建一個CompletableFuture ,一旦所有指定的期貨都完成,該CompletableFuture將完成,因此,任何相關的連鎖操作都將在所有期貨都已完成之后運行。 通過使用thenApply我們創建了一個依存的thenApply ,它將以result()的返回值完成。

如果result()並非要返回值,而只是要在所有其他動作完成后才運行的動作,則可以使用

CompletableFuture.allOf(
    CompletableFuture.runAsync(() -> method1()),
    CompletableFuture.runAsync(() -> method2())
).thenRun(() -> result());

代替。

一種簡單的方法是將您的Runnable提交給ExecutorService,然后調用shutdown ,然后調用awaitTermination

ExecutorService executor = Executors.newWorkStealingPool();
executor.submit(task);
executor.submit(task);

executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

無需使用CompletableFuture。

保存到您創建的線程的鏈接,然后調用join()

Thread a = new Thread(task);
Thread b = new Thread(task);
a.start();
b.start();

a.join();
b.join();
//guaranteed that both threads have completed here

根據您想要多少控制權,您可以使用ThreadPoolExecutor:

tpe.execute(Runnable);

等待有效計數== 0;

然后關閉執行器。

或者將線程保持在一個結構中。

等待特定的TTL,然后在狀態為RUNNABLE時中斷它們

暫無
暫無

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

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