gpt4 book ai didi

java - "synchronized"方法与 "synchronized (Class.class)"

转载 作者:行者123 更新时间:2023-11-29 05:22:21 27 4
gpt4 key购买 nike

我正在阅读 Android 示例中的 BluetoothChatService.java 文件,有一件事特别让我感到困惑。

  • 方法在多个位置访问静态成员,并且定义为同步
  • 在另一部分中,正在访问同一个静态成员,但是使用类级同步而不是同步方法。
  • 还有另一种方法不是同步的,而是使用synchronized(this)

有人可以解释一下使用不同技术的原因吗?

源代码可在 BluetoothChatService.java 获得以下是我所说的一些 fragment :

private int mState;

// Constants that indicate the current connection state
public static final int STATE_NONE = 0;
public static final int STATE_LISTEN = 1;
public static final int STATE_CONNECTING = 2;
public static final int STATE_CONNECTED = 3;

同步方法:

public synchronized void start() {
...
setState(STATE_LISTEN);
...
}

同步块(synchronized block)(类级):

if (socket != null) {
synchronized (BluetoothChatService.this) {
switch (mState) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice(),
mSocketType);
break;
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate new socket.
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close unwanted socket", e);
}
break;
}
}
}

同步(this):

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

最佳答案

在所有情况下,都会对 BluetoothChatService 的当前实例进行锁定。

1- 同步 (BluetoothChatService.this)

用于在另一个类中编写代码,可以是 BluetoothChatService 中的匿名类。为了引用 BluetoothChatService 的实例。

2- 同步(this)

在 BluetoothChatService 的任何成员函数中使用。哪个指向它的实例。

3- synchronized void start()

在整个方法需要同步时使用。相当于

void start(){ synchronized (this){

在前两种情况下,函数的其他部分(不在同步块(synchronized block)内)不需要线程安全,在函数名前放置一个 synchronized 关键字将使整个函数线程安全,并且作为结果将使您的应用程序必然变慢。

关于java - "synchronized"方法与 "synchronized (Class.class)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24169223/

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