0

可能重复:
这种同步的意义何在?

我正在使用 BluetoothChat 示例应用程序来建立我的蓝牙连接,并且在第 218 行有一个东西让我非常烦恼:

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);
}

为什么需要同步ConnectedThread实例的本地副本,而不是同步write函数来做到这一点(无论是在内部ConnectedThread还是上面的方法中)。我想可以同时write从不同的线程多次调用,但我总是看到同步的方法,而不是实例的副本。

4

1 回答 1

0

Synchronize不适合ConnectedThread用于mState读取和更新。

于 2012-09-05T10:08:48.487 回答