Motivation
Parallelitätsdienstprogramme in java.util.concurrent
Gebrauchskategorien:
Konkurrierende Sammlungen
Eigenschaften:
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); }
Vorteile:
Synchronisatoren
Zweck: Koordination zwischen Threads.
Beispiel für gängige Synchronisierer:
Praxisbeispiel: Gleichzeitiges Timing mit CountDownLatch
Ziel: Messen Sie die Ausführungszeit mehrerer Threads gleichzeitig.
Implementierung:
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; }
Hinweise:
Aktuelle Praxis mit Warten und Benachrichtigen
Wird nur für die Wartung von Legacy-Code benötigt.
Hauptregeln:
synchronized (lock) { while (!condition) { lock.wait(); } }
Fazit
Beispiele aus dem Buch
Das obige ist der detaillierte Inhalt vonElement Bevorzugen Sie Nebenläufigkeitsdienstprogramme zum Warten und Benachrichtigen. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!