gpt4 book ai didi

java - Android 示例蓝牙聊天应用程序中此空分配的目的是什么

转载 作者:行者123 更新时间:2023-12-01 12:03:29 26 4
gpt4 key购买 nike

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

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 没有多大意义。

关于java - Android 示例蓝牙聊天应用程序中此空分配的目的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27846026/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com