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.
}
同步方法
1234
public synchronized void method() {
// Thread.currentThread() has a lock on this object, i.e. a synchronized method is the same as
// calling { synchronized(this) {…} }.
}
/**
* 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;
}
}