介绍
Semaphore是一种基于计数的信号量。它可以设定一个阈值,基于此,多个线程竞争获取许可信号,做自己的申请后归还,超过阈值后,线程申请许可信号将会被阻塞。Semaphore可以用来构建一些对象池,资源池之类的,比如数据库连接池,我们也可以创建计数为1的Semaphore,将其作为一种类似互斥锁的机制,这也叫二元信号量,表示两种互斥状态。它的用法如下:
availablePermits函数用来获取当前可用的资源数量
wc.acquire(); //申请资源
wc.release();// 释放资源
应用场景
semphore可以实现synchronized和lock的功能。
模拟网吧,只有两台机器,但是有五人排队上网。代码如下:
public class ThreadSemaphore {
public static void main(String[] args) throws Exception {
Semaphore computer = new Semaphore(2);//该网吧2台机
new InternetBar(computer,"【青铜】").start();
new InternetBar(computer,"【白银】").start();
new InternetBar(computer,"【黄金】").start();
new InternetBar(computer,"【白金】").start();
new InternetBar(computer,"【最强王者】").start();
}
}
class InternetBar extends Thread{
Semaphore computer;//电脑
String name;//上机者名称
public InternetBar(Semaphore computer,String name) {
super();
this.computer = computer;
this.name = name;
}
public void run() {
try {
computer.acquire();
System.out.println("欢迎:"+name+",在"+(computer.availablePermits()+1)+"号机!");
System.out.println(name+": 可以打撸了!");
Thread.sleep(1000);
System.out.println(name+": 游戏胜利!");
} catch (Exception e) {
} finally {
computer.release();
}
}
}