AsynHelper Java 라이브러리에는 이러한 비동기 호출 (및 대기)을위한 유틸리티 클래스 / 메소드 세트가 포함되어 있습니다.
메소드 호출 또는 코드 블록 세트를 비동기식으로 실행하려는 경우 아래 스 니펫과 같이 유용한 헬퍼 메소드 AsyncTask .submitTasks가 포함 됩니다.
AsyncTask.submitTasks(
() -> getMethodParam1(arg1, arg2),
() -> getMethodParam2(arg2, arg3)
() -> getMethodParam3(arg3, arg4),
() -> {
//Some other code to run asynchronously
}
);
모든 비동기 코드가 실행을 완료 할 때까지 기다리려면 AsyncTask.submitTasksAndWait 변수를 사용할 수 있습니다.
또한 각 비동기 메서드 호출 또는 코드 블록에서 반환 값을 얻으려면 AsyncSupplier .submitSuppliers 를 사용하여 메서드에서 반환 한 결과 공급자 배열에서 결과를 얻을 수 있습니다. 다음은 샘플 스 니펫입니다.
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);
각 메소드의 리턴 유형이 다르면 아래 스 니펫을 사용하십시오.
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());
비동기 메소드 호출 / 코드 블록의 결과는 아래 스 니펫과 동일한 스레드 또는 다른 스레드의 다른 코드 지점에서 얻을 수도 있습니다.
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());