gpt4 book ai didi

java - Java 中用于线程间使用的互斥体?

转载 作者:行者123 更新时间:2023-12-01 18:58:54 25 4
gpt4 key购买 nike

我想要 Java 中的互斥体,它让我可以在一个线程中等待它并在另一个线程中释放它。我知道我可以使用容量为 1 的信号量,但问题是“acquire()”方法会抛出“InterruptedException”。 Java中有没有专门的同步方法来实现这个目的?

最佳答案

幸运的是,Semaphore 为您提供了这个方法:)

public void acquireUninterruptibly()

Acquires a permit from this semaphore, blocking until one is available. Acquires a permit, if one is available and returns immediately, reducing the number of available permits by one.

If no permit is available then the current thread becomes disabled for thread scheduling purposes and lies dormant until some other thread invokes the release() method for this semaphore and the current thread is next to be assigned a permit.

If the current thread is interrupted while waiting for a permit then it will continue to wait, but the time at which the thread is assigned a permit may change compared to the time it would have received the permit had no interruption occurred. When the thread does return from this method its interrupt status will be set.

关于java - Java 中用于线程间使用的互斥体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13017683/

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