首先锁一般来说是互斥的,排他的,而信号量则指的是一种允许设定数量个线程进入
的一种共享锁,但是有数量限制,当进入的个数达到上限则开始不允许其他的进入。
public void acquire()获取许可
public void acquire(int i)获取多个许可
public void release()释放许可
public void release(int i)释放多个许可
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* @Author:minglu
* @Description:
* @Date: 2018/11/27
*/
public class SemaphoreDemo implements Runnable {
final Semaphore semaphore = new Semaphore(5);//五个许可的共享锁
@Override
public void run() {
try {
semaphore.acquire();
Thread.sleep(2000);
System.out.println(Thread.currentThread().getId()+"Done!");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(20);
SemaphoreDemo semaphoreDemo = new SemaphoreDemo();
for (int i = 0; i < 20; i++) {
executorService.submit(semaphoreDemo);
}
}
}
会发现上述代码输出,为5个5个输出,因为许可只有5个,拿了之后2秒后才释放
释放了别的才拿。