这是大多数在线资源中写的代码。但这个代码不正确,因为考虑一种情况:当一个线程被阻塞时,然后被中断。即使它没有获取锁,该线程仍将释放锁。这是不正确的。那么在Java中释放信号量的正确实现是什么?
Semaphore lock = new Semaphore(1);
add(){
try {
lock.acquire();
// critical section
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}finally{
lock.release()
}
}
我认为这是正确的解决方案:-. 对吗?
try {
lock.acquire();
try {
// do some stuff here
} finally {
lock.release();
}
} catch(InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException(ie);
}