gpt4 book ai didi

java - 在理解线程等待和通知方面需要帮助

转载 作者:搜寻专家 更新时间:2023-11-01 01:57:05 24 4
gpt4 key购买 nike

class Semaphore {
private int count=100;
public Semaphore(int n) {
this.count = n;
}

public synchronized void acquire() {
while(count == 0) {
try {
wait();
} catch (InterruptedException e) {
//keep trying
}
}
count--;
}

public synchronized void release() {
count++;
notify(); //alert a thread that's blocking on this semaphore
}
}

目前我支持 100 个用户。如果请求来自 jsp(客户端)并通过此类,Thread(来自 JSP 的请求)是否会自动等待通知

最佳答案

我强烈推荐使用 java.util.concurrent.Semaphore从标准库而不是编写自定义信号量实现。仅提及为什么这通常是一个更好的主意的一个原因:notify 不提供任何 FIFO 保证(来自 Object.notify() ):

The choice is arbitrary and occurs at the discretion of the implementation

关于java - 在理解线程等待和通知方面需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6394870/

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