Semaphore
2024-10-16 17:35:02
信号量玩的也是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结束。
最新文章
- [LeetCode] Transpose File 转置文件
- HDU 5816 Hearthstone
- hdu 3518(后缀数组)
- git diff old mode 100755 new mode 100644
- Crashing Robots
- 修复关于apache-xampp的问题:Port 443 in use by “vmware-hostd.exe”!
- JavaScript学习笔记(十二)——箭头函数(Arrow Function)
- 微信小程序开发教程目录
- Python面面面
- (转)c# control.Invoke control.BeginInvoke
- [转]PHP与Shell交互
- springboot自定义jmx对象
- java通过各种类型驱动连接数据库
- HH实习 acm算法部 1689
- textView 添加超链接(两种实现方式)
- 调试.NET程序OutOfMemoryException (转载)
- Leetcode 974. Subarray Sums Divisible by K
- 最短Hamilton路径-状压dp解法
- Careercup | Chapter 2
- 基于BASYS2的VHDL程序——数字钟(改进版)
热门文章
- java-collections.sort异常Comparison method violates its general contract!
- centos 防火墙
- ubuntu/mint 安装google的拼音输入法
- BZOJ 2882: 工艺
- 【BZOJ-2325】道馆之战 树链剖分 + 线段树
- 简单实用的Log4net帮助类
- wcf第4步之原生调用简单封装
- 在Application中集成Microsoft Translator服务之开发前准备
- 数据库大数据处理---复制(SQLServer)
- 清北学堂模拟赛day7 错排问题