1 回答

TA貢獻1856條經(jīng)驗 獲得超11個贊
除了繁忙的等待(這會阻塞整個 CPU 并快速耗盡電池)之外,我看不到任何同步。有共享數(shù)據(jù)結(jié)構(gòu)(可能是stopMessageThread、characteristicWriteSuccessful和messageQueue)和多個訪問它們的線程。如果沒有同步,就會出現(xiàn)競爭條件,并且堵塞可能是其表現(xiàn)。
所以我建議采用更簡單的設計,特別是沒有用于發(fā)送消息的線程:
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不會阻塞并且速度很快。這是一個安全的假設,因為該方法在設計上是異步的:它有一個回調(diào),將在操作完成時調(diào)用。
因此回調(diào)onCharacteristicWrite用于發(fā)送緩沖區(qū)中的下一條消息。因此,對線程的需求消失了——相關(guān)的復雜性也消失了。
當從后臺線程調(diào)用回調(diào)時,仍然涉及多個線程。因此,對共享數(shù)據(jù)的訪問是同步的。
添加回答
舉報