gpt4 book ai didi

java - 如何让异步监听器阻塞?

转载 作者:行者123 更新时间:2023-11-30 09:41:34 25 4
gpt4 key购买 nike

我正在编写一个黑莓应用程序,它使用基于文本的 AT 命令与简单的蓝牙外围设备进行通信——类似于调制解调器……我只能使用事件监听器让它在黑莓上运行。所以通信现在是异步的。

但是,由于它是一个简单的设备并且我需要控制并发访问,所以我更愿意只进行阻塞调用。

我有以下代码试图通过使用等待/通知将通信转换为阻塞。但是当我运行它时,在 getStringValue 完成之前,notifyResults 永远不会运行。即无论延迟如何,它总是会超时。

btCon 对象已经在单独的线程上运行。

我确定我遗漏了一些关于线程的明显信息。有好心人指点一下吗?

谢谢

我还应该添加 notifyAll 爆炸并引发 IllegalMonitorStateException。

我之前尝试过使用一个简单的 boolean 标志和一个等待循环。但同样的问题也存在。在 getStringValue 完成之前,notifyResult 永远不会运行。

public class BTCommand implements ResultListener{
String cmd;
private BluetoothClient btCon;
private String result;

public BTCommand (String cmd){
this.cmd=cmd;
btCon = BluetoothClient.getInstance();
btCon.addListener(this);

System.out.println("[BTCL] BTCommand init");
}

public String getStringValue(){
result = "TIMEOUT";
btCon.sendCommand(cmd);
System.out.println("[BTCL] BTCommand getStringValue sent and waiting");

synchronized (result){
try {
result.wait(5000);
} catch (InterruptedException e) {
System.out.println("[BTCL] BTCommand getStringValue interrupted");
}
}//sync
System.out.println("[BTCL] BTCommand getStringValue result="+result);

return result;
}

public void notifyResults(String cmd) {
if(cmd.equalsIgnoreCase(this.cmd)){
synchronized(result){
result = btCon.getHash(cmd);
System.out.println("[BTCL] BTCommand resultReady: "+cmd+"="+result);
result.notifyAll();
}//sync
}
}

}

最佳答案

由于 notifyResults 和 getStringValue 在同一个对象上都有同步子句,假设 getStringValues 首先到达同步部分,notifyResults 将阻塞在同步子句的开头,直到 getStringValues 退出同步区域。如果我理解,这就是您所看到的行为。

Nicholas 的建议可能不错,但您可能在您使用的 BlackBerry API 中找不到任何这些实现​​。您可能想看看 produce-consumer模式。

关于java - 如何让异步监听器阻塞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8975701/

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