在 Java java.util.concurrent.Semaphore 文档中,我不太清楚如果 semaphore.acquire() 阻塞线程并随后被 InterruptedException 中断会发生什么。信号量值是否已经减小,是否需要释放信号量?
目前我正在使用这样的代码:
try {
// use semaphore to limit number of parallel threads
semaphore.acquire();
doMyWork();
}
finally {
semaphore.release();
}
或者在 acquire() 期间发生 InterruptedException 时我是否应该不调用 release() ?
最佳答案
call release() when an InterruptedException occurs during acquire() ?
你不应该。如果 .acquire() 被中断,则不会获取信号量,因此可能不应该释放它。
你的代码应该是
// use semaphore to limit number of parallel threads
semaphore.acquire();
try {
doMyWork();
}
finally {
semaphore.release();
}
关于java - 如果 semaphore.acquire() 得到 InterruptedException,需要 semaphore.relase()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12104978/