Javaで並列に複数の機能を呼び出すための短い手はありますか?

マシュー・ルージュ;

私は多くの作業を行う必要があり、Javaの機能を持って考えます。この作品は、独自の関数で定義されており、互いに独立していている行うには、いくつかの異なるもの、で構成されています。

void myFunction() {
    foo();
    bar();
}

しかし、これらの機能は、ここでは必要ではなく、必要以上に長く実行関数全体を作る次々に(私はそれをコード化と同じように)、実行します。独自のスレッドで両方の機能を実行すると、かなり多くのコードが必要です。

void myFunction() {
    UncaughtExceptionHandler eh = (th, t) -> { throw new UndeclaredThrowableException(t); };
    try {
        Thread foo = new Thread(() -> foo());
        Thread bar = new Thread(() -> bar());
        foo.setUncaughtExceptionHandler(eh);
        bar.setUncaughtExceptionHandler(eh);
        foo.start();
        bar.start();
        foo.join();
        bar.join();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

ある場合、私は疑問に思うので、いくつかは、内蔵の新しいJavaのバージョンでアプローチ、より効率的のようなものをこれを行うには:

Threads.doParallel(
    () -> foo(),
    () -> bar()
);
ボウモア:

私はCompletableFuturesを使用して、取得する最短のはこれです:

CompletableFuture.allOf(
        CompletableFuture.runAsync(new FutureTask<Void>(() -> foo(), null)),
        CompletableFuture.runAsync(new FutureTask<Void>(() -> bar(), null))
).get();

これは、中excptionsのため取り扱いがないfoo()かをbar()しかし、我々はいくつかの簡潔さを犠牲にする、それを追加することができます。

CompletableFuture.allOf(
        CompletableFuture.runAsync(new FutureTask<Void>(() -> foo(), null)),
        CompletableFuture.runAsync(new FutureTask<Void>(() -> bar(), null))
)
.exceptionally(t -> {
    throw new UndeclaredThrowableException(t);
})
.get();

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=313116&siteId=1
おすすめ