몇 가지 변형이 있습니다. 내가 그 질문을 올바르게 이해한다면, 나는 당신이 # 5를 찾고 있다고 생각한다.
// 1. Static method
public static synchronized void doSomething() {
// Mutually exclusive for all calls
}
// 2. Static w/ Shared lock
private static Object STATIC_LOCK = new Object();
public static void staticMethod1() {
synchronized (STATIC_LOCK) {
// Mutually exclusive across staticMethod1() and staticMethod2()
}
}
public static void staticMethod2() {
synchronized (STATIC_LOCK) {
// Mutually exclusive across staticMethod1() and staticMethod2()
}
}
// 3. Instance method
public synchronized void doSomethingElse() {
// Mutually exclusive per instance of class
}
// 4. Instance w/ Shared lock
private Object lock = new Object();
public static void method1() {
synchronized (lock) {
// Mutually exclusive across method1() and method2() for each class instance
}
}
public static void method2() {
synchronized (lock) {
// Mutually exclusive across method1() and method2() for each class instance
}
}
// 5. Instance method synchronization across multiple class instances
private static Object SHARED_LOCK = new Object();
public void commonInstanceMethod() {
synchronized (SHARED_LOCK) {
// Mutually exclusive across all class instances
}
}
공유 객체를 잠급니다. 'static' 필드에 저장된'ReentrantLock'을 사용하거나'static' 필드에 저장된'Object'에'synchronized'를 사용하십시오. – Andreas