動機
java.util.concurrent 中的同時實用程式
實用類別:
競賽系列
特徵:
Map<String, String> map = new ConcurrentHashMap<>(); String result = map.putIfAbsent("key", "value"); if (result == null) { System.out.println("Valor inserido."); } else { System.out.println("Chave já existente com valor: " + result); }
好處:
同步器
目的:線程之間的協調。
常見同步器範例:
實際範例:使用 CountDownLatch 進行並發計時
目的:測量多個執行緒同時執行的時間。
實作:
public static long time(Executor executor, int concurrency, Runnable action) throws InterruptedException { CountDownLatch ready = new CountDownLatch(concurrency); CountDownLatch start = new CountDownLatch(1); CountDownLatch done = new CountDownLatch(concurrency); for (int i = 0; i < concurrency; i++) { executor.execute(() -> { try { ready.countDown(); // Indica que está pronto start.await(); // Aguarda o sinal de início action.run(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { done.countDown(); // Indica que terminou } }); } ready.await(); // Aguarda todas as threads ficarem prontas long startTime = System.nanoTime(); start.countDown(); // Dispara o sinal de início done.await(); // Aguarda todas as threads finalizarem return System.nanoTime() - startTime; }
註:
等待和通知的當前實踐
僅用於遺留程式碼維護。
主要規則:
synchronized (lock) { while (!condition) { lock.wait(); } }
結論
書中的例子
以上是項目 喜歡並發實用程式來等待和通知的詳細內容。更多資訊請關注PHP中文網其他相關文章!