Semaphore 可以理解为一个阈值,正在进行的操作数量不能超过此阈值,可以用来限制资源的访问,或者控制某个队列中对象的个数。
public class SemaphoreTest {
private Semaphore semaphore = new Semaphore(2);
public void m() {
try {
System.out.println(Thread.currentThread().getName()+" started");
semaphore.acquire();
Thread.sleep((int) (Math.random() * 2000));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
System.out.println(Thread.currentThread().getName()+" ended");
}
public static void main(String[] args) {
SemaphoreTest test = new SemaphoreTest();
for (int i=0;i<8; i++) {
new Thread(()->test.m()).start();
}
}
}