Semaphore(int permits,boolean fair):构造方法,当fair等于true时,创建具有给定许可数的计数信号量并设置为公平信号量。
int availablePermits():返回此信号量中当前可用的许可数。
void acquire():表示从此信号量获取一个许可,并将可用许可数减1。如果当前信号量没有许可可获取,线程将被阻塞。
void release():用于释放一个许可,并将其返回给信号量,同时将可用许可数加1。
import java.util.Random;
import java.util.concurrent.Semaphore;
/**
* Semaphore的使用
* 场景:模拟一个厕所只有2个坑位,有5个人(编号1-5)先后来上厕所,采用先来先上的策略。
*/
public class UseSemaphore {
private static class UseRunner implements Runnable{
private String name;
private Semaphore semaphore;
public UseRunner(String name, Semaphore semaphore){
this.name = name;
this.semaphore = semaphore;
}
@Override
public void run() {
System.out.print(name + "憋死了。。。");
if(semaphore.availablePermits() > 0){
System.out.println("谢天谢地,有坑位!");
}else{
System.out.println("这么倒霉,没有坑位了,等会吧!");
}
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + "终于轮到我了,拉尿就是爽!");
SleepTools.second(new Random().nextInt(10)+ 5);
System.out.println(name + "拉完了,好臭!");
semaphore.release();
}
}
public static void main(String[] args){
Semaphore semaphore = new Semaphore(2,true);
for(int i = 0; i < 5; i++){
Thread thread = new Thread(new UseRunner("第" + (i+1) + "个人", semaphore));
thread.start();
SleepTools.second(2);
}
}
}
import java.util.concurrent.TimeUnit;
/**
* 线程休眠辅助工具类
*/
public class SleepTools {
/**
* 按秒休眠
* @param seconds 秒数
*/
public static final void second(int seconds){
try {
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 按毫秒数休眠
* @param millis 毫秒数
*/
public static final void milli(int millis){
try {
TimeUnit.MILLISECONDS.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}