- Semaphore 是共享锁的一种,字面上意思就是信号量锁
- 顾名思义,一个可以共享的锁,可以让多个线程共享同一把锁,例如同一条马路可以让 4 台车同时并行跑,相当于可以让 4 个线程共享一把锁,临界区的限制也就是 4
- 会有一个临界区,用于控制线程,只有拿到信号量(许可)才能的进入
- 一个线程可以拿多个许可,但是一般情况不会这样做,还是看业务需求咯~~
- 常常用在并发控制的场景
主要 api
名称 | 用法 |
---|---|
acquire() | 获取一个信号量(许可) |
acquire(int permits) | 获取 permits 数量的信号量,在获取到 permits 数量的信号量之前会一直阻塞等待,并且数量必须小于等于 Semaphore 允许的总信号量,否则会出现死锁 |
acquireUninterruptibly() | 获取一个不可被中断的信号量 |
tryAcquire() | 尝试去回去一个信号量,获取到了,返回 true,否则 false |
tryAcquire(long timeout, TimeUnit unit) | 在限定时间内尝试去回去一个信号量,获取到了,返回 true,否则 false |
release() | 释放当前的信号量 |
release(int permits) | 同样,上面获取了多少个信号量,这里就需要释放多少个,否则容易出现死锁一直等待的情况 |
简要使用
public class TestSemaphore {
// 限定线程数量
private static final Semaphore semaphore = new Semaphore(3);
static class TestThread implements Runnable {
@Override
public void run() {
try {
semaphore.acquire(2);
System.out.println(System.currentTimeMillis() + " :" + Thread.currentThread().getName() + " 进来了");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release(2);
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new TestThread(), "Thread TestThread1");
Thread t2 = new Thread(new TestThread(), "Thread TestThread2");
Thread t3 = new Thread(new TestThread(), "Thread TestThread3");
Thread t4 = new Thread(new TestThread(), "Thread TestThread4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
输出
1537843926834 :Thread TestThread1 进来了
1537843929834 :Thread TestThread3 进来了
1537843932835 :Thread TestThread2 进来了
1537843935835 :Thread TestThread4 进来了