android 示例蓝牙聊天应用程序中此空分配的目的是什么
what is the purpose of this null assignment in the android sample bluetooth chat application
我只是在连接方法中分析 android 示例应用程序之一 - 蓝牙聊天:https://developer.android.com/samples/BluetoothChat/project.html . I'm looking at the BluetoothChatService class ( 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 就被新值覆盖了。
在此代码的前面将 mConnectThread
设置为 null 比较安全,以防在它被设置为新值之前抛出异常。这样,无论是否分配新值,旧实例都可用于垃圾回收。
但是,在这种方法中,肯定会有更好的操作顺序。通常你是对的,在分配新值之前将它设置为 null 没有多大意义。
我只是在连接方法中分析 android 示例应用程序之一 - 蓝牙聊天:https://developer.android.com/samples/BluetoothChat/project.html . I'm looking at the BluetoothChatService class ( 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 就被新值覆盖了。
在此代码的前面将 mConnectThread
设置为 null 比较安全,以防在它被设置为新值之前抛出异常。这样,无论是否分配新值,旧实例都可用于垃圾回收。
但是,在这种方法中,肯定会有更好的操作顺序。通常你是对的,在分配新值之前将它设置为 null 没有多大意义。