Java 信号量停止线程

Java Semaphore Stop Threads

大家下午好,

我正在为一个学校项目使用 Java 的信号量和并发性,并且有几个关于它如何工作的问题!

如果没有可用的许可,我需要线程退出 "queue" - 而不是在准备好之前休眠。这可能吗?正如您在我的 try, catch, finally 中看到的那样 - 此事件没有句柄:

try {
    semaphore.acquire();
    System.out.println(Thread.currentThread().getName() + " aquired for 3 seconds " + semaphore.toString());
    Thread.sleep(3000);
}
catch (InterruptedException e) {
   e.printStackTrace();
} finally {   
   semaphore.release();
   System.out.println(Thread.currentThread().getName() + " released " + semaphore.toString());
}

Daniel 提出了 tryAquire 函数 - 这看起来不错,但我读过的教程指出信号量需要一个 try, catch, finally 块来防止 死锁 .我当前的代码(实现 tryAquire)将在 finally 块中释放,即使从未获取该线程也是如此。你有什么建议吗?

public void seatCustomer(int numBurritos) {
    try {
        if(semaphore.tryAcquire()) {
            System.out.println(Thread.currentThread().getName() + " aquired for 3 seconds " + semaphore.toString());
            Thread.sleep(3000); 
        } else {
            System.out.println(Thread.currentThread().getName() + " left due to full shop");
        }

    }
    catch (InterruptedException e) {
       e.printStackTrace();
    } finally {   
       semaphore.release();
       System.out.println(Thread.currentThread().getName() + " released " + semaphore.toString());
    }
}

我建议您阅读 Semaphor 的 JavaDocs。特别是,查看 tryAcquire 方法。

Acquires a permit from this semaphore, only if one is available at the time of invocation.

Acquires a permit, if one is available and returns immediately, with the value true, reducing the number of available permits by one.

If no permit is available then this method will return immediately with the value false.

这意味着您可以尝试获得许可证(如果有的话)。如果 none 可用,此方法 returns 立即返回 false 而不是阻塞。

您必须让“finally”块更智能一些。

boolean hasPermit = false;
try {
    hasPermit = semaphore.tryAcquire();
    if (hasPermit) {
        // do stuff.
    }
} finally {
    if (hasPermit) {
       semaphore.release();
    }
}