动机
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中文网其他相关文章!