static synchronized methods?

30947 ワード

Keep in mind that using synchronized on methods is really just shorthand (assume class is SomeClass):
synchronized static void foo() {     ... } 

is the same as
static void foo() {     synchronized(SomeClass.class) {         ...     } } 

and
synchronized void foo() {     ... } 

is the same as
void foo() {     synchronized(this) {         ...     } } 

You can use any object as the lock. If you want to lock subsets of static methods, you can
class SomeClass {     private static final Object LOCK_1 = new Object();     private static final Object LOCK_2 = new Object();     static void foo() {         synchronized(LOCK_1) {...}     }     static void fee() {         synchronized(LOCK_1) {...}     }     static void fie() {         synchronized(LOCK_2) {...}     }     static void fo() {         synchronized(LOCK_2) {...}     } } 

(for non-static methods, you would want to make the locks be non-static fields)