ไลบรารี AsynHelper Java ประกอบด้วยชุดของคลาส / วิธีการยูทิลิตี้สำหรับการโทรแบบอะซิงโครนัส (และรอ)
หากต้องการเรียกใช้ชุดการเรียกเมธอดหรือบล็อคโค้ดแบบอะซิงโครนัสกระบวนการจะรวมเมธอดตัวช่วยเหลือที่มีประโยชน์AsyncTask .submitTasksตามด้านล่างตัวอย่าง
AsyncTask.submitTasks(
() -> getMethodParam1(arg1, arg2),
() -> getMethodParam2(arg2, arg3)
() -> getMethodParam3(arg3, arg4),
() -> {
//Some other code to run asynchronously
}
);
หากต้องการรอจนกว่ารหัสอะซิงโครนัสทั้งหมดจะทำงานเสร็จสมบูรณ์AsyncTask.submitTasksAndWait varient สามารถใช้งานได้
นอกจากนี้หากต้องการรับค่าส่งคืนจากการเรียกใช้เมธอดแบบอะซิงโครนัสหรือการบล็อกรหัสแต่ละครั้งสามารถใช้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());