2018-08-10 13:58:28 1275瀏覽
今天扣丁學(xué)堂Java培訓(xùn)老師給大家介紹一下關(guān)于Java實(shí)現(xiàn)Promise.all()的示例代碼,下面一起跟隨小編過來看看吧。
public class Promise { private static ExecutorService executorService = Executors.newScheduledThreadPool(16); private Promise() { throw new AssertionError(); } /** * 實(shí)現(xiàn)并發(fā)同時(shí)地對某個(gè)action并發(fā)執(zhí)行并返回執(zhí)行結(jié)果 * 實(shí)現(xiàn)思路: * 并發(fā)創(chuàng)建所有執(zhí)行的線程,并通過鎖(start)阻塞等待著 * 在創(chuàng)建所有執(zhí)行的線程后(ready)開始計(jì)時(shí),并解鎖然所有的線程啟動 * 通過另外一個(gè)鎖(done)記錄執(zhí)行完的線程 * 主線程只需關(guān)心3點(diǎn) * - 所有線程是否準(zhǔn)備好 * - 準(zhǔn)備好的話開始計(jì)時(shí)并解鎖開始執(zhí)行 * - 等待執(zhí)行完畢 * * @param callableList 要并發(fā)執(zhí)行的列表 * @return list 執(zhí)行結(jié)果,list.item為null的話表示執(zhí)行異常 * @throws InterruptedException 異常 */ public static <T> List<T> all(final List<Callable<T>> callableList) throws InterruptedException { final List<T> result = new ArrayList<>(); int length = callableList.size(); final CountDownLatch ready = new CountDownLatch(length); final CountDownLatch start = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(length); for (final Callable<T> callable : callableList) { executorService.execute(new Runnable() { @Override public void run() { ready.countDown(); try { start.await(); T t = callable.call(); result.add(t); } catch (Exception e) { // interrupt when exception Thread.currentThread().interrupt(); // set null mean exception result.add(null); e.printStackTrace(); } finally { done.countDown(); } } }); } ready.await(); long startnano = System.nanoTime(); start.countDown(); done.await(); long cause = System.nanoTime() - startnano; System.out.println(String.format("Promise all done,cause time millSecond: %s", cause / 1000000)); return result; } }
public void promiseAllTest() throws Exception{ List<Callable<String>> callables = new ArrayList<>(); for (int i = 0; i < 10; i++) { int finalI = i; callables.add(new Callable<String>() { @Override public String call() throws Exception { int millis = new Random().nextInt(10000); Thread.sleep(millis); System.out.println(String.format("thread%s sleep %s millis" ,finalI,millis)); return "Thread" + finalI; } }); } List<String> result = Promise.all(callables); System.out.println(result); System.out.println("done..."); }
thread1 sleep 732 millis thread2 sleep 758 millis thread7 sleep 976 millis thread8 sleep 1397 millis thread5 sleep 1513 millis thread0 sleep 2221 millis thread3 sleep 4885 millis thread6 sleep 5221 millis thread4 sleep 7101 millis thread9 sleep 7634 millis Promise all done,cause time millSecond: 7638 [Thread1, Thread2, Thread7, Thread8, Thread5, Thread0, Thread3, Thread6, Thread4, Thread9] done...
本文只是通過原生Java實(shí)現(xiàn)簡單版本的Promise.all(),可用于簡單的并發(fā)編程,但是對于實(shí)際高并發(fā)應(yīng)用還需要優(yōu)化,如對線程池的優(yōu)化,還有中斷的處理等,想要了解更多關(guān)于Java開發(fā)內(nèi)容的小伙伴可以登錄扣丁學(xué)堂官網(wǎng)咨詢,扣丁學(xué)堂Java視頻教程讓學(xué)員免費(fèi)觀看學(xué)習(xí),扣丁學(xué)堂Java技術(shù)交流群:670348138。
【關(guān)注微信公眾號獲取更多學(xué)習(xí)資料】
查看更多關(guān)于“Java開發(fā)資訊”的相關(guān)文章>>