static Semaphore semaphore = new Semaphore(5);
public static void main(String[] args) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 3, 1,
TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(5),
new ThreadPoolExecutor.CallerRunsPolicy());
for (int i = 0; i < 50; i++) {
executor.submit(new Task());
}
try {
Thread.sleep(50000);
executor.shutdownNow();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static class Task implements Runnable{
@Override
public void run() {
if (semaphore.tryAcquire()) {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+":get");
Thread.sleep(2000);
semaphore.release();
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
当 tryAcquire 和 acquire 同时出现时,需要执行两次release方法
因为 tryAcquire 和 acquire 方法都会执行一次尝试CAS(1)的方法 导致同时消耗两个信号 若只执行一次release方法会造成信号量回填速度跟不上消耗速度导致所有参与当前 semaphore 的线程全部阻塞。
tryAcquire()--> sync.nonfairTryAcquireShared(1) >= 0;
final int nonfairTryAcquireShared(int acquires) {
for (;;) {
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining)) //直接子类cas
}
}
出现一次cas消耗信号量操作
acquire()--> sync.acquireSharedInterruptibly(1);
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
} //----->
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg); //回调子类 cas
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
两者都会操作 cas 用来消耗信号量
因此当需要获取permit信号量时,二者等价 只需要选用其中一个即可
二者的差别:
tryAcquire返回的是一个bool 可直接用作判断是否成功
acquire执行了一个可中断方法,可能出现中断异常
如有理解错误,请斧正