是否可以替换不会阻塞的以下Java代码?我只想ping可能的等待线程。我不想在监视器中已经存在的可能线程上进行任何更改。
synchronized( monitor ) {
monitor.notify();
}
最佳答案
您可以使用java.util.concurrent.Semaphore代替Monitor。二进制信号量可以与同步块(synchronized block)具有相同的用途:
private final Semaphore sema = new Semaphore(1, true); // binary: only 1 permit
....
try {
sema.acquire(); // blocks till permit is available
try {
// critical section code
....
} finally {
sema.release(); // release permit
}
} catch (InterruptedException ie) {
....
您可以使用以下方法检查信号量的状态:
sema.availablePermits() // 1 if no threads in critical section
sema.getQueueLength() // number of threads blocked waiting on acquire
sema.getQueuedThreads() // list of threads blocked waiting on acquire