![](/img/trans.png)
[英]Confusing Java synchronized method, synchronized(this), and synchronized class
[英]“synchronized” method vs. “synchronized (Class.class)”
我正在从Android示例中读取BluetoothChatService.java
文件,有一件事让我感到困惑。
synchronized(this)
代替。 有人可以解释使用不同技术的原因吗?
源代码可以在BluetoothChatService.java上找到 ,这里有一些我正在讨论的片段:
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块(类级) :
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;
}
}
}
synchronized(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- synchronized (BluetoothChatService.this)
当代码写在另一个类中时使用,可以是BluetoothChatService
内的匿名类。 为了引用BluetoothChatService
实例。
2- synchronized (this)
用于BluetoothChatService的任何成员函数内。 哪个指向它的实例。
3- synchronized void start()
在需要同步整个方法时使用。 它相当于
void start(){ synchronized (this){
在前两种情况下,函数的其他部分(不在同步块内),不需要是线程安全的,并且在函数名之前放置一个synchronized
关键字会使整个函数线程安全,结果会使你的应用程序变慢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.