信号量

信号量类Semaphore,用来保护对唯一共享资源的访问。一个简单的打印队列,并发任务进行打印,加入信号量同时之能有一个线程进行打印任务 。

import java.util.concurrent.Semaphore;

public class PrintQueue {
public PrintQueue() { semaphore = new Semaphore(1,true);
} private final Semaphore semaphore; public void printJob(Object document) {
try {
semaphore.acquire(); long duration = (long) (Math.random() * 10); System.out.println("执行打印"+Thread.currentThread().getName() + "花费时间"+ duration+ "秒");
Thread.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
semaphore.release();
}
}
} public class Job implements Runnable{ private PrintQueue printQueue; public Job(PrintQueue printQueue){ this.printQueue=printQueue;
}
@Override
public void run() {
printQueue.printJob(new Object());
System.out.println("文档被打印"+Thread.currentThread().getName());
}
} public class Main {
public static void main(String[] args) {
PrintQueue p = new PrintQueue();
Thread thread[] = new Thread[10];
for (int i = 0; i <thread.length; i++) {
thread[i]=new Thread(new Job(p),"Thread"+i);
}
for (int i = 0; i < thread.length; i++) {
thread[i].start();
}
}
}
----------------------输出结果 ---------------------------
执行打印Thread0花费时间9秒
文档被打印Thread0
执行打印Thread3花费时间9秒
文档被打印Thread3
执行打印Thread2花费时间6秒
文档被打印Thread2
执行打印Thread1花费时间4秒
文档被打印Thread1
执行打印Thread5花费时间6秒
文档被打印Thread5
执行打印Thread7花费时间3秒
文档被打印Thread7
执行打印Thread9花费时间8秒
文档被打印Thread9
执行打印Thread8花费时间0秒
文档被打印Thread8
执行打印Thread6花费时间8秒
文档被打印Thread6
执行打印Thread4花费时间7秒
文档被打印Thread4
如上声明一个打印队列,构造器初始化信号量对象来保护对打印队列的访问。semaphore.acquire();获取信号量,最后semaphore.release();用来释放。启动10个线程进行打印的操作,第一个获得信号量的线程将能访问临界区,其余的线程将被信号量阻塞,直到信号量的释放。信号量被释放后,将选择一个正在等待的线程并且允许它访问临界区。

简单代码分析


根据boolean fair ,来构建公平和非公平的信号量
/**
* Creates a {@code Semaphore} with the given number of
* permits and the given fairness setting.
*
* @param permits the initial number of permits available.
* This value may be negative, in which case releases
* must occur before any acquires will be granted.
* @param fair {@code true} if this semaphore will guarantee
* first-in first-out granting of permits under contention,
* else {@code false}
*/
public Semaphore(int permits, boolean fair) {
sync = (fair)? new FairSync(permits) : new NonfairSync(permits);
} FairSync 和 NonfairSync 继承Sync 类,然而Sync 类继承 AbstractQueuedSynchronizer
/**
* Synchronization implementation for semaphore. Uses AQS state
* to represent permits. Subclassed into fair and nonfair
* versions.
*/
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 p = getState();
if (compareAndSetState(p, p + releases))
return true;
}
} final void reducePermits(int reductions) {
for (;;) {
int current = getState();
int next = current - reductions;
if (compareAndSetState(current, next))
return;
}
} final int drainPermits() {
for (;;) {
int current = getState();
if (current == 0 || compareAndSetState(current, 0))
return current;
}
}
}

参考文献

Java并发编程

AbstractQueuedSynchronizer

Java并发编程Semaphore的更多相关文章

  1. Java并发编程-Semaphore

    基于AQS的前世今生,来学习并发工具类Semaphore.本文将从Semaphore的应用场景.源码原理解析来学习这个并发工具类. 1. 应用场景 Semaphore用来控制同时访问某个特定资源的操作 ...

  2. 【Java并发编程实战】-----“J.U.C”:Semaphore

    信号量Semaphore是一个控制访问多个共享资源的计数器,它本质上是一个"共享锁". Java并发提供了两种加锁模式:共享锁和独占锁.前面LZ介绍的ReentrantLock就是 ...

  3. Java并发编程:CountDownLatch、CyclicBarrier和Semaphore

    Java并发编程:CountDownLatch.CyclicBarrier和Semaphore 在java 1.5中,提供了一些非常有用的辅助类来帮助我们进行并发编程,比如CountDownLatch ...

  4. Java并发编程的4个同步辅助类(CountDownLatch、CyclicBarrier、Semaphore、Phaser)

    我在<JDK1.5引入的concurrent包>中,曾经介绍过CountDownLatch.CyclicBarrier两个类,还给出了CountDownLatch的演示案例.这里再系统总结 ...

  5. Java并发编程:CountDownLatch、CyclicBarrier和Semaphore (总结)

    下面对上面说的三个辅助类进行一个总结: 1)CountDownLatch和CyclicBarrier都能够实现线程之间的等待,只不过它们侧重点不同: CountDownLatch一般用于某个线程A等待 ...

  6. 14、Java并发编程:CountDownLatch、CyclicBarrier和Semaphore

    Java并发编程:CountDownLatch.CyclicBarrier和Semaphore 在java 1.5中,提供了一些非常有用的辅助类来帮助我们进行并发编程,比如CountDownLatch ...

  7. 【转】Java并发编程:CountDownLatch、CyclicBarrier和Semaphore

    Java并发编程:CountDownLatch.CyclicBarrier和Semaphore   Java并发编程:CountDownLatch.CyclicBarrier和Semaphore 在j ...

  8. java并发编程系列原理篇--JDK中的通信工具类Semaphore

    前言 java多线程之间进行通信时,JDK主要提供了以下几种通信工具类.主要有Semaphore.CountDownLatch.CyclicBarrier.exchanger.Phaser这几个通讯类 ...

  9. Java并发编程基础三板斧之Semaphore

    引言 最近可以进行个税申报了,还没有申报的同学可以赶紧去试试哦.不过我反正是从上午到下午一直都没有成功的进行申报,一进行申报 就返回"当前访问人数过多,请稍后再试".为什么有些人就 ...

随机推荐

  1. Spark算子--coalesce和repartition

    coalesce和repartition--Transformation类算子 代码示例

  2. Spark学习笔记2(spark所需环境配置

    Spark学习笔记2 配置spark所需环境 1.首先先把本地的maven的压缩包解压到本地文件夹中,安装好本地的maven客户端程序,版本没有什么要求 不需要最新版的maven客户端. 解压完成之后 ...

  3. 如何完成域名和ip地址的绑定

    首先,我们要知道什么是域名绑定,所谓域名绑定就是是指已选定的域名与服务器主机的空间绑定,实在是在域名注册查询上设置或者WEB服务器上设置,使一个域名被指导向一特定空间,从而使访问者访问你的域名的时候就 ...

  4. twitter的ID生成器的snowFlake算法的自造版

    snowFlake算法在生成ID时特别高效,可参考:https://segmentfault.com/a/1190000011282426 SnowFlake算法生成id的结果是一个64bit大小的整 ...

  5. MySQL Index Merge Optimization

    Index Merge用在通过一些range scans得到检索数据行和合并成一个整体.合并可以通过 unions,intersections,或者unions-intersection运用在底层的扫 ...

  6. 武侠--生活--java

    一.名词解释 1.向上转型 大白话:村支书通知你爸去大队领过年发的面粉,结果你爸不在家,你装成你爸去了,村支书一看,行,你具有你爸的所有功能,就给了你. 官方解释:子类引用的对象转换为父类类型称为向上 ...

  7. RocketMQ-事务消费

    理论部分在https://www.jianshu.com/p/453c6e7ff81c中的 "三.事务消息".下面从代码层面看一下rockemq的事务消息 一.事务消费端. 从代码 ...

  8. 手把手教学系列:从零开始配置VPS服务器

    1.什么是VPS? 百度百科:VPS(Virtual Private Server 虚拟专用服务器)技术,将一台服务器分割成多个虚拟专享服务器的优质服务. 通俗地讲,可以认为就是一台放在机房机架上的服 ...

  9. string用法总结

    要想使用标准C++中的string类,必须要包含#include <string> 注意是<string>而不是<string.h>,带.h的是C语言中的头文件 s ...

  10. 使用SoapUI调用Vsphere Web Service

    项目中经常需要调用Webservice进行验证测试,下面就介绍下如何使用测试工具SoapUI调用Vsphere vcenter的 Web Service VSphere的Webservice地址默认为 ...