【并发编程】AQS学习

时间:2023-03-09 17:03:49
【并发编程】AQS学习
【并发编程】AQS学习

一个简单的示例:

  1. package net.jcip.examples;
  2. import java.util.concurrent.locks.*;
  3. import net.jcip.annotations.*;
  4. /**
  5.  * OneShotLatch
  6.  * <p/>
  7.  * Binary latch using AbstractQueuedSynchronizer
  8.  *
  9.  * @author Brian Goetz and Tim Peierls
  10.  */
  11. @ThreadSafe
  12. public class OneShotLatch {
  13.     private final Sync sync = new Sync(); //基于委托的方式
  14.     public void signal() {
  15.         sync.releaseShared(0); ////会调用 tryAcquireShared
  16.     }
  17.     public void await() throws InterruptedException {
  18.         sync.acquireSharedInterruptibly(0); //会调用 tryAcquireShared
  19.     }
  20.     private class Sync extends AbstractQueuedSynchronizer { //内部私有类
  21.         protected int tryAcquireShared(int ignored) {
  22.             // Succeed if latch is open (state == 1), else fail
  23.             return (getState() == 1) ? 1 : -1;
  24.         }
  25.         protected boolean tryReleaseShared(int ignored) {
  26.             setState(1); // Latch is now open
  27.             return true; // Other threads may now be able to acquire
  28.         }
  29.     }
  30. }






附件列表