信号量玩的也是aqs的state。

package com.hust.grid.leesf.semaphore;

import java.util.concurrent.Semaphore;

class MyThread extends Thread {
private Semaphore semaphore;

public MyThread(String name, Semaphore semaphore) {
    super(name);
    this.semaphore = semaphore;
}

public void run() {
    int count = 3;
    System.out.println(Thread.currentThread().getName() + " trying to acquire");
    try {
        semaphore.acquire(count);
        System.out.println(Thread.currentThread().getName() + " acquire successfully");
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        semaphore.release(count);
        System.out.println(Thread.currentThread().getName() + " release successfully");
    }
}
}

public class SemaphoreDemo {
public final static int SEM_SIZE = 10;

public static void main(String[] args) {
    Semaphore semaphore = new Semaphore(SEM_SIZE);
    MyThread t1 = new MyThread("t1", semaphore);
    MyThread t2 = new MyThread("t2", semaphore);
    t1.start();
    t2.start();
    int permits = 5;
    System.out.println(Thread.currentThread().getName() + " trying to acquire");
    try {
        semaphore.acquire(permits);
        System.out.println(Thread.currentThread().getName() + " acquire successfully");
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        semaphore.release();
        System.out.println(Thread.currentThread().getName() + " release successfully");
    }

}
}

说以说白了没有什么难度。

首先分配10个信号量。

第一个分走了5个。

第二个分走了3个,也还能跑。

第三个不够数了,所以只能照例park了,然后自己躺在待解救的aqs sync队列中。

上面有人爽完了,释放了几个坑,第三个也就解脱了。

最终,所有人都爽完了,aqs状态变回10结束。

最新文章

  1. [LeetCode] Transpose File 转置文件
  2. HDU 5816 Hearthstone
  3. hdu 3518(后缀数组)
  4. git diff old mode 100755 new mode 100644
  5. Crashing Robots
  6. 修复关于apache-xampp的问题:Port 443 in use by “vmware-hostd.exe”!
  7. JavaScript学习笔记(十二)——箭头函数(Arrow Function)
  8. 微信小程序开发教程目录
  9. Python面面面
  10. (转)c# control.Invoke control.BeginInvoke
  11. [转]PHP与Shell交互
  12. springboot自定义jmx对象
  13. java通过各种类型驱动连接数据库
  14. HH实习 acm算法部 1689
  15. textView 添加超链接(两种实现方式)
  16. 调试.NET程序OutOfMemoryException (转载)
  17. Leetcode 974. Subarray Sums Divisible by K
  18. 最短Hamilton路径-状压dp解法
  19. Careercup | Chapter 2
  20. 基于BASYS2的VHDL程序——数字钟(改进版)

热门文章

  1. java-collections.sort异常Comparison method violates its general contract!
  2. centos 防火墙
  3. ubuntu/mint 安装google的拼音输入法
  4. BZOJ 2882: 工艺
  5. 【BZOJ-2325】道馆之战 树链剖分 + 线段树
  6. 简单实用的Log4net帮助类
  7. wcf第4步之原生调用简单封装
  8. 在Application中集成Microsoft Translator服务之开发前准备
  9. 数据库大数据处理---复制(SQLServer)
  10. 清北学堂模拟赛day7 错排问题