![](/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.