Semaphore
他的作用是控制访问特定资源的线程数目。
# 设置许可线程的数量
public Semaphore(int permits)
# fair表示公平性,如果这个设置为true的话,下次执行的线程会是等待最久的线程
public Semaphore(int permits, boolean fair)
# 阻塞获取许可
public void acquire() throws InterruptedException
# 释放许可
public void release()
代码实现
public class SemaphoreDemo {
static class TaskThread extends Thread {
Semaphore semaphore;
public TaskThread(Semaphore semaphore) {
this.semaphore = semaphore;
}
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(getName() + " acquire");
Thread.sleep(1000);
semaphore.release();
System.out.println(getName() + " release ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
int threadNum = 5;
Semaphore semaphore = new Semaphore(2);
for (int i = 0; i < threadNum; i++) {
new TaskThread(semaphore).start();
}
}
}
主要的应用场景用于限流
ReentrantLock
- java中已经有了内置锁,synchronized,synchronized的特点是使用简单,一切交给jvm去处理。不需要显示释放。
- 从用法上可以看出,synchronized稍微复杂一点,因为必须在finally中进行解锁,如果不在finally中解锁,有可能代码出现异常锁没被释放。
- ReentrantLock并不是一种替代内置加锁的方法,而是作为一种可选择的高级功能。
- 相比于synchronized,reentrantlock在功能上更加丰富,它具有可重入,可中断,可限时、公平锁等特点。
# 可中断
lock.lockInterruptibly();
# 可重入锁
lock.lock();
# 可限时
lock.tryLock(long timeout, TimeUnit unit)
# 公平锁
public ReentrantLock(boolean fair)
网友评论