gpt4 book ai didi

java - 如果 semaphore.acquire() 得到 InterruptedException,需要 semaphore.relase()?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:52:57 26 4
gpt4 key购买 nike

在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com