1 回答

TA貢獻1856條經驗 獲得超11個贊
除了繁忙的等待(這會阻塞整個 CPU 并快速耗盡電池)之外,我看不到任何同步。有共享數據結構(可能是stopMessageThread、characteristicWriteSuccessful和messageQueue)和多個訪問它們的線程。如果沒有同步,就會出現競爭條件,并且堵塞可能是其表現。
所以我建議采用更簡單的設計,特別是沒有用于發送消息的線程:
private ArrayList<byte[]> messageQueue = new ArrayList<byte[]>();
private boolean isSending = false;
void sendMessage(byte[] message) {
synchronized (this) {
if (isSending) {
messageQueue.add(message);
return;
}
isSending = true;
}
customCharacteristic.setValue(message);
bluetoothGatt.writeCharacteristic(customCharacteristic);
}
public void onCharacteristicWrite (BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
byte[] message;
synchronized (this) {
if (messageQueue.size() == 0) {
isSending = false;
return;
}
message = messageQueue.remove(0);
}
customCharacteristic.setValue(message);
bluetoothGatt.writeCharacteristic(customCharacteristic);
}
該解決方案的假設是writeCharacteristic不會阻塞并且速度很快。這是一個安全的假設,因為該方法在設計上是異步的:它有一個回調,將在操作完成時調用。
因此回調onCharacteristicWrite用于發送緩沖區中的下一條消息。因此,對線程的需求消失了——相關的復雜性也消失了。
當從后臺線程調用回調時,仍然涉及多個線程。因此,對共享數據的訪問是同步的。
添加回答
舉報