这里同步的意义何在?
为什么不直接使用 mConnectedThread.write(out)
?
代码 fragment 来自 Android 的 BluetoothChat 示例 (found here)
/**
* Write to the ConnectedThread in an unsynchronized manner
* @param out The bytes to write
* @see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) return;
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
最佳答案
需要同步以确保您没有不一致的状态。
如果没有同步,代码将是:
public void write(byte[] out) {
if (mState != STATE_CONNECTED) return;
mConnectedThread.write(out);
}
现在,如果 if 语句检查和方法调用之间的连接在哪里关闭,mConnectedThread
可能会在方法调用执行之前被分配为 null。这将导致 NullPointerException
。
关于java - 这个同步有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1982649/