1. Semaphore 是什么?
Semaphore 字面意思是信号量的意思,它的作用是控制访问特定资源的线程数目。
2. 怎么使用 Semaphore?
2.1 构造方法
public Semaphore(int permits)
public Semaphore(int permits, boolean fair)
permits 表示许可线程的数量
fair 表示公平性,如果这个设为 true 的话,下次执行的线程会是等待最久的线 程
2.2 重要方法
public void acquire() throws InterruptedException
public void release()
tryAcquire(long timeout, TimeUnit unit)
acquire() 表示阻塞并获取许可
release() 表示释放许可
2.3 基本使用
2.3.1 需求场景
资源访问,服务限流。
2.3.2 代码实现
import java.util.concurrent.Semaphore;
/**
* @description :可用于流量控制,限制最大的并发访问数
*/
public class SemaphoreSample {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(2);
for (int i=0;i<5;i++){
new Thread(new Task(semaphore,"silas+"+i)).start();
}
}
static class Task extends Thread{
Semaphore semaphore;
public Task(Semaphore semaphore,String tname){
this.semaphore = semaphore;
this.setName(tname);
}
public void run() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+":acquire() at time:"+System.currentTimeMillis());
Thread.sleep(2000);
semaphore.release();
System.out.println(Thread.currentThread().getName()+":release() at time:"+System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
打印结果:
Thread-1:acquire() at time:1571208530724
Thread-3:acquire() at time:1571208530727
Thread-1:release() at time:1571208532725
Thread-5:acquire() at time:1571208532725
Thread-3:release() at time:1571208532727
Thread-7:acquire() at time:1571208532727
Thread-5:release() at time:1571208534726
Thread-9:acquire() at time:1571208534726
Thread-7:release() at time:1571208534728
Thread-9:release() at time:1571208536727
Process finished with exit code 0
从打印结果可以看出,一次只有两个线程执行 acquire(),只有线程进行 release() 方法后 才会有别的线程执行 acquire()。