在Java的并发包中,Semaphore类表示信号量。Semaphore内部主要通过AQS(AbstractQueuedSynchronizer)实现线程的管理。Semaphore有两个构造函数,参数permits表示许可数,它最后传递给了AQS的state值。线程在运行时首先获取许可,

如果成功,许可数就减1,线程运行,当线程运行结束就释放许可,许可数就加1。

如果许可数为0,则获取失败,线程位于AQS的等待队列中,它会被其它释放许可的线程唤醒。在创建Semaphore对象的时候还可以指定它的公平性。

一般常用非公平的信号量,非公平信号量是指在获取许可时先尝试获取许可,

而不必关心是否已有需要获取许可的线程位于等待队列中,如果获取失败,才会入列。

而公平的信号量在获取许可时首先要查看等待队列中是否已有线程,如果有则入列。

先看测试案例:

package com.cxy.cyclicBarrier;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit; /**
* Created by Administrator on 2017/4/10.
*/
public class CxyDemo {
private final static int threadCount = ; public static void main(String[] args) throws Exception { ExecutorService exec = Executors.newCachedThreadPool(); final Semaphore semaphore = new Semaphore(); for (int i = ; i < threadCount; i++) {
System.out.println(i+"----------------------");
final int threadNum = i;
exec.execute(() -> {
try {
if (semaphore.tryAcquire(, TimeUnit.MILLISECONDS)) { // 尝试获取一个许可
test(threadNum);
semaphore.release(); // 释放一个许可
}
} catch (Exception e) {
// log.error("exception" , e);
System.out.println(e);
}
});
}
exec.shutdown();
} private static void test(int threadNum) throws Exception {
// log.info("{}" , threadNum);
System.out.println("a"+threadNum);
Thread.sleep();
} }

执行结果:

源码分析:

构造方法:

 public Semaphore(int permits) {
sync = new NonfairSync(permits);
} /**
* 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);
}

第一个构造方法:是允许的信号量

第二个,里面传入的boolean参数,采用的是公平锁还是分公平锁

tryAcquire源码
 public boolean tryAcquire(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(, unit.toNanos(timeout));
} public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
return tryAcquireShared(arg) >= ||
doAcquireSharedNanos(arg, nanosTimeout);
} private boolean doAcquireSharedNanos(int arg, long nanosTimeout)
throws InterruptedException {
if (nanosTimeout <= 0L)
return false;
final long deadline = System.nanoTime() + nanosTimeout;
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= ) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return true;
}
}
nanosTimeout = deadline - System.nanoTime();
if (nanosTimeout <= 0L)
return false;
if (shouldParkAfterFailedAcquire(p, node) &&
nanosTimeout > spinForTimeoutThreshold)
LockSupport.parkNanos(this, nanosTimeout);
if (Thread.interrupted())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
release源码
    public void release() {
sync.releaseShared();
} public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
} private void doReleaseShared() {
/*
* Ensure that a release propagates, even if there are other
* in-progress acquires/releases. This proceeds in the usual
* way of trying to unparkSuccessor of head if it needs
* signal. But if it does not, status is set to PROPAGATE to
* ensure that upon release, propagation continues.
* Additionally, we must loop in case a new node is added
* while we are doing this. Also, unlike other uses of
* unparkSuccessor, we need to know if CAS to reset status
* fails, if so rechecking.
*/
for (;;) {
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {
if (!compareAndSetWaitStatus(h, Node.SIGNAL, ))
continue; // loop to recheck cases
unparkSuccessor(h);
}
else if (ws == &&
!compareAndSetWaitStatus(h, , Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}

JUC包下Semaphore学习笔记的更多相关文章

  1. JUC包下CyclicBarrier学习笔记

    CyclicBarrier,一个同步辅助类,在API中是这么介绍的: 它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point).在涉及一组固定大小的线程的程序中,这 ...

  2. JUC包下CountDownLatch学习笔记

    CountDownLatch的作用是能使用多个线程进来之后,且线程任务执行完毕之后,才执行, 闭锁(Latch):一种同步方法,可以延迟线程的进度直到线程到达某个终点状态.通俗的讲就是,一个闭锁相当于 ...

  3. Linux下iptables学习笔记

    Linux下iptables学习笔记 在Centos7版本之后,防火墙应用已经由从前的iptables转变为firewall这款应用了.但是,当今绝大多数的Linux版本(特别是企业中)还是使用的6. ...

  4. YOLO---Darknet下的学习笔记 V190319

    YOLO---Darknet下的学习笔记 @WP 20190319 很久没有用YOlO算法了,今天又拿过来玩玩.折腾半天,才好运行通的,随手记一下: 一是,终端下的使用.二是,python接口的使用. ...

  5. YOLO---Darknet下的学习笔记

    YOLO.V3-Darknet下的学习笔记 @wp20180927 [目录] 一. 安装Darknet(仅CPU下) 2 1.1在CPU下安装Darknet方式 2 1.2在GPU下安装Darknet ...

  6. JUC.Lock(锁机制)学习笔记[附详细源码解析]

    锁机制学习笔记 目录: CAS的意义 锁的一些基本原理 ReentrantLock的相关代码结构 两个重要的状态 I.AQS的state(int类型,32位) II.Node的waitStatus 获 ...

  7. 20135202闫佳歆--week5 系统调用(下)--学习笔记

    此为个人笔记存档 week 5 系统调用(下) 一.给MenuOS增加time和time-asm命令 这里老师示范的时候是已经做好的了: rm menu -rf 强制删除 git clone http ...

  8. juc包:使用 juc 包下的显式 Lock 实现线程间通信

    一.前置知识 线程间通信三要素: 多线程+判断+操作+通知+资源类. 上面的五个要素,其他三个要素就是普通的多线程程序问题,那么通信就需要线程间的互相通知,往往伴随着何时通信的判断逻辑. 在 java ...

  9. 【Java多线程】JUC包下的工具类CountDownLatch、CyclicBarrier和Semaphore

    前言 JUC中为了满足在并发编程中不同的需求,提供了几个工具类供我们使用,分别是CountDownLatch.CyclicBarrier和Semaphore,其原理都是使用了AQS来实现,下面分别进行 ...

随机推荐

  1. 【原】Coursera—Andrew Ng机器学习—编程作业 Programming Exercise 2——逻辑回归

    作业说明 Exercise 2,Week 3,使用Octave实现逻辑回归模型.数据集  ex2data1.txt ,ex2data2.txt 实现 Sigmoid .代价函数计算Computing ...

  2. 并发之AtomicIntegerArray

    5 并发之AtomicIntegerArray     该类是Java对Integer数组支持的原子性操作:在认识这个类之前我们先来看一个方法,这个方法是Integer类中的:  public sta ...

  3. 581. Shortest Unsorted Continuous Subarray连续数组中的递增异常情况

    [抄题]: Given an integer array, you need to find one continuous subarray that if you only sort this su ...

  4. oracle获取表和列的备注

    using System;using System.Collections.Generic;using System.Data;using System.Linq;using System.Runti ...

  5. 编译boost,去掉不使用的组件

    说明:下面内容仅针对Linux环境(boost官网为:http://www.boost.org/,可从这里下载它的源代码包,这里要求下载.tar.gz包,而非.7z..zip或bz2包). 在当前目录 ...

  6. Matlab和Python用于深度学习应用研究哪个好?

    Matlab和Python都有一些关于深度学习的开源的解决方案(caffe\DeepMind\TensorFlow),基于哪个开展应用研究好?

  7. 关于Java异常一段很有意思的代码

    今天学习了Java的异常,讲到try-catch-finally时,老师演示了一段代码,觉得很有意思,很能反映出其执行的过程,让自己有点绕,特意记录一下. 只要代码执行到try代码内部, 不管有没有异 ...

  8. LibreOJ 6002 最小路径覆盖(最大流)

    题解:最小路径覆盖=总点数减去最大匹配数,拆点,按照每条边前一个点连源点,后一个点连汇点跑最大流,即可跑出最大匹配数,然后减一减就可以了~ 代码如下: #include<queue> #i ...

  9. POJ3026 Borg Maze(bfs求边+最小生成树)

    Description The Borg is an immensely powerful race of enhanced humanoids from the delta quadrant of ...

  10. java8之流的基本使用(二)

    概述 流(stream())是java8的一个新特性,主要的作用就是将各种类型的集合转换为流,然后的方便迭代数据用的.例如: //将List类型的集合转换为流 list.stream() 转换为流之后 ...