第81条 并发工具优先于 wait 和 notify
比较常见的同步器:
CountDownLatch
、Semaphore
、CyclicBarrier
、Exchanger
、Phaser
-
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(() -> { ready.countDown(); // Tell timer we're ready try { start.await(); // Wait till peers are ready action.run(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { done.countDown(); // Tell timer we're done } }); } ready.await(); // Wait for all workers to be ready long startNanos = System.nanoTime(); start.countDown(); // And they're off! done.await(); // Wait for all workers to finish return System.nanoTime() - startNanos; }
始终应该使用 while 循环模式来调用 wait 方法;永远不要在循环之外调用 wait 方法
不应该在新代码中使用
wait
和notify
思考
- 应该有空了解下Java的concurrent库提供的内容,由Doug Lea开发的AQS
-
wait
和notify
本身并不会太重要,但是基本的原理还是要了解下。本科期间找实习,一个笔试题就是让用这两个函数,实现两个线程,按顺序输出26个英文字母