【发布时间】:2011-11-13 04:39:51
【问题描述】:
我有一个管理几个远程设备(Capsules)的 Android 蓝牙应用程序。
向 Capsule 的套接字输出流写入数据昨天工作,在仅对 Android 应用程序进行中等规模重构后,我收到以下错误:
java.lang.IllegalMonitorStateException: 尝试解锁读锁,未被当前线程锁定。
这里是socket创建代码:
public final void connectWithCapsule(Capsule capsule)
throws Exception {
BluetoothSocket socket = capsulesSockets.get(capsule);
if (socket == null) {
try {
// Method m = capsule.getBT_Device().getClass().getMethod("createRfcommSocket", new Class[]{int.class});
// socket = (BluetoothSocket) m.invoke(capsule.getBT_Device(), Integer.valueOf(17));
socket = capsule.getBT_Device().createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
} catch (Exception e) {
logError("Error creating RFcomm socket", e);
throw e;
}
capsulesSockets.put(capsule, socket);
}
try {
socket.connect();
} catch (IOException e) {
logError("Error connecting socket", e);
try {
socket.close();
} catch (IOException e1) {
logError("Error closing socket", e1);
}
capsulesSockets.remove(capsule);
throw e;
}
}
以及管理输入/输出流的模型:
public final class KitBT_ConnectionModel {
private final OutputStream[] outputStreams;
private final InputStream[] inputStreams;
public KitBT_ConnectionModel(OutputStream[] outputStreams, InputStream[] inputStreams) {
super();
this.outputStreams = outputStreams;
this.inputStreams = inputStreams;
}
public void transmitData(byte[] bs)
throws IOException {
for (OutputStream outputStream : outputStreams) {
outputStream.write(bs); // THIS LINE THROWS THE EXCEPTION
outputStream.flush();
}
}
public InputStream[] getInputStreams() {
return inputStreams;
}
}
注意:我没有对两个流执行任何操作,第一次写入会导致异常。
首先想到的是哪个线程在什么时候设置了读锁?
我尝试使用调用套接字创建的线程和流事务,我已经 确定,100% 确定他们两者都有已被 相同 线程访问(并且还尝试使用不同线程访问),但此异常仍然存在。
请赐教...
【问题讨论】:
标签: android multithreading bluetooth