Java 程式設計/關鍵字/synchronized
外觀
synchronized 是一個關鍵字。
它標記了一個臨界區。臨界區是指只有一個執行緒可以執行的程式碼段。因此,要進入標記的程式碼,執行緒必須同步,一次只能進入一個執行緒,其他執行緒必須等待。有關更多資訊,請參見 執行緒同步方法 或 [1].
synchronized 關鍵字可以以兩種方式使用
- 建立一個
synchronized塊 - 標記一個方法為
synchronized
一個 synchronized 塊標記為
程式碼段 1: 同步塊。
synchronized(<object_reference>) {
// Thread.currentThread() has a lock on object_reference. All other threads trying to access it will
// be blocked until the current thread releases the lock.
}
|
標記方法 synchronized 的語法為
程式碼段 2: 同步方法。
public synchronized void method() {
// Thread.currentThread() has a lock on this object, i.e. a synchronized method is the same as
// calling { synchronized(this) {…} }.
}
|
同步始終與一個物件相關聯。如果方法是靜態的,則關聯的物件是類。如果方法是非靜態的,則關聯的物件是例項。雖然允許將 抽象 方法宣告為 synchronized,但這樣做沒有意義,因為同步是實現的一部分,而不是宣告的一部分,而抽象方法沒有實現。
例如,我們可以展示一個執行緒安全的單例模式版本
程式碼清單 1: Singleton.java
/**
* The singleton class that can be instantiated only once with lazy instantiation
*/
public class Singleton {
/** Static class instance */
private volatile static Singleton instance = null;
/**
* Standard private constructor
*/
private Singleton() {
// Some initialisation
}
/**
* Getter of the singleton instance
* @return The only instance
*/
public static Singleton getInstance() {
if (instance == null) {
// If the instance does not exist, go in time-consuming
// section:
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
|