ssslinppp

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
AQS.png

一个简单的示例:

  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. }










附件列表

     

    posted on 2016-05-12 11:33  ssslinppp  阅读(211)  评论(0编辑  收藏  举报