我正在分析一个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。
答案 0 :(得分:1)
如果在将代码设置为新值之前抛出异常,则在此代码中将mConnectThread
设置为null更安全。这样,无论是否分配了新值,旧实例都可用于垃圾回收。
然而,人们当然可以争论这种方法中更好的一系列行动。通常情况下,在分配新值之前,将它设置为null并不是很重要。