在android示例蓝牙聊天应用程序中这个null赋值的目的是什么

时间:2015-01-08 17:26:15

标签: java android android-bluetooth

我正在分析一个Android示例应用程序 - 蓝牙聊天:https://developer.android.com/samples/BluetoothChat/project.html。我在connect方法中查看了BluetoothChatService类(https://developer.android.com/samples/BluetoothChat/src/com.example.android.bluetoothchat/BluetoothChatService.html)。那里有这样的代码:

public synchronized void connect(BluetoothDevice device, boolean secure) {
    Log.d("@@@", "connect to: " + device);
    // Cancel any thread attempting to make a connection
    if (mState == STATE_CONNECTING) {
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }
    }
    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
        mConnectedThread.cancel();
        mConnectedThread = null;
    }
    // Start the thread to connect with the given device
    mConnectThread = new ConnectThread(device, secure);
    mConnectThread.start();
    setState(STATE_CONNECTING);
}

我不明白这条线的目的是什么:

mConnectThread = null;

看起来这条线路没用 - 无论如何,只需几行就可以用新值覆盖mConnectThread。

1 个答案:

答案 0 :(得分:1)

如果在将代码设置为新值之前抛出异常,则在此代码中将mConnectThread设置为null更安全。这样,无论是否分配了新值,旧实例都可用于垃圾回收。

然而,人们当然可以争论这种方法中更好的一系列行动。通常情况下,在分配新值之前,将它设置为null并不是很重要。