Die AsynHelper- Java-Bibliothek enthält eine Reihe von Dienstprogrammklassen / -methoden für solche asynchronen Aufrufe (und Wartezeiten).
Wenn eine Reihe von Methodenaufrufen oder Codeblöcken asynchron ausgeführt werden soll, enthält es eine nützliche Hilfsmethode AsyncTask .submitTasks wie im folgenden Snippet.
AsyncTask.submitTasks(
() -> getMethodParam1(arg1, arg2),
() -> getMethodParam2(arg2, arg3)
() -> getMethodParam3(arg3, arg4),
() -> {
//Some other code to run asynchronously
}
);
Wenn gewartet werden soll, bis alle asynchronen Codes vollständig ausgeführt wurden, kann die Variable AsyncTask.submitTasksAndWait verwendet werden.
Wenn ein Rückgabewert von jedem asynchronen Methodenaufruf oder Codeblock abgerufen werden soll, kann der AsyncSupplier .submitSuppliers verwendet werden, sodass das Ergebnis von dem von der Methode zurückgegebenen Array der Ergebnislieferanten abgerufen werden kann. Unten ist das Beispiel-Snippet:
Supplier<Object>[] resultSuppliers =
AsyncSupplier.submitSuppliers(
() -> getMethodParam1(arg1, arg2),
() -> getMethodParam2(arg3, arg4),
() -> getMethodParam3(arg5, arg6)
);
Object a = resultSuppliers[0].get();
Object b = resultSuppliers[1].get();
Object c = resultSuppliers[2].get();
myBigMethod(a,b,c);
Wenn sich der Rückgabetyp jeder Methode unterscheidet, verwenden Sie die folgende Art von Snippet.
Supplier<String> aResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam1(arg1, arg2));
Supplier<Integer> bResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam2(arg3, arg4));
Supplier<Object> cResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam3(arg5, arg6));
myBigMethod(aResultSupplier.get(), bResultSupplier.get(), cResultSupplier.get());
Das Ergebnis der asynchronen Methodenaufrufe / Codeblöcke kann auch an einem anderen Codepunkt im selben Thread oder an einem anderen Thread wie im folgenden Snippet abgerufen werden.
AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam1(arg1, arg2), "a");
AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam2(arg3, arg4), "b");
AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam3(arg5, arg6), "c");
//Following can be in the same thread or a different thread
Optional<String> aResult = AsyncSupplier.waitAndGetFromSupplier(String.class, "a");
Optional<Integer> bResult = AsyncSupplier.waitAndGetFromSupplier(Integer.class, "b");
Optional<Object> cResult = AsyncSupplier.waitAndGetFromSupplier(Object.class, "c");
myBigMethod(aResult.get(),bResult.get(),cResult.get());