Semaphore
来源:互联网 发布:网络市场中间商的类型 编辑:程序博客网 时间:2024/06/16 21:48
1.类声明:
public class Semaphore implements java.io.Serializable {}
2.变量:
//同步器,用来实现Semaphoreprivate final Sync sync;
3.方法:
//自定义同步器 abstract static class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 1192457210091910933L; Sync(int permits) { setState(permits); } final int getPermits() { return getState(); } final int nonfairTryAcquireShared(int acquires) { for (;;) { int available = getState(); int remaining = available - acquires; if (remaining < 0 || compareAndSetState(available, remaining)) return remaining; } } protected final boolean tryReleaseShared(int releases) { for (;;) { int current = getState(); int next = current + releases; if (next < current) // overflow throw new Error("Maximum permit count exceeded"); if (compareAndSetState(current, next)) return true; } } final void reducePermits(int reductions) { for (;;) { int current = getState(); int next = current - reductions; if (next > current) // underflow throw new Error("Permit count underflow"); if (compareAndSetState(current, next)) return; } } final int drainPermits() { for (;;) { int current = getState(); if (current == 0 || compareAndSetState(current, 0)) return current; } } } //不公平的版本,阻塞之后被唤醒时,不管先来的还是后来的一律等同试待 static final class NonfairSync extends Sync { private static final long serialVersionUID = -2694183684443567898L; NonfairSync(int permits) { super(permits); } protected int tryAcquireShared(int acquires) { return nonfairTryAcquireShared(acquires); } } /** * Fair version */ //公平版本的同步器,阻塞之后,按照先来先访问的原则访问 static final class FairSync extends Sync { private static final long serialVersionUID = 2014338818796000944L; FairSync(int permits) { super(permits); } protected int tryAcquireShared(int acquires) { for (;;) { if (hasQueuedPredecessors()) return -1; int available = getState(); int remaining = available - acquires; if (remaining < 0 || compareAndSetState(available, remaining)) return remaining; } } } //获取通行证,若没有则一直阻塞直到获取通行证或者被中断 public void acquire() throws InterruptedException { sync.acquireSharedInterruptibly(1); } //释放通行证 public void release() { sync.releaseShared(1); }
阅读全文
0 0
- Semaphore
- semaphore
- semaphore
- Semaphore
- Semaphore
- semaphore
- Semaphore
- semaphore
- Semaphore
- Semaphore
- Semaphore
- semaphore
- Semaphore
- Semaphore
- semaphore
- Semaphore
- semaphore
- Semaphore
- c3p0参数解释
- 1<<i 和 if(i&(1<<j))的用法
- iptables 详解
- 百度之星1002 度度熊的王国战略 并查
- C#特性
- Semaphore
- python的base64
- Python 玩具 —— 使用 os , reuqests 配合 you-get 自动下载网易公开课视频
- Yii2学习笔记:关于params['breadcrumbs'][]
- Spring Ioc的基本原理及其xml的实现方法(上)
- MyEclipse 2016 在部署启动新项目时报 Could not publish to the server. java.lang.IndexOutOfBoundsException 解决办法
- lua math库
- A*寻路算法入门(一)
- AutoTURN v6.01 1CD(车辆转弯模拟软件)\