I have an question about synchronized static methods.
If i invoke a synchronized static method, does it mean i lock this class and other method (including static or no static) can not be accessed before the synchronized static method end?
When A synchronized static method is locking class object, why the other static method can be invoked at the same time?
class Y {
static synchronized void staticSleep() {
System.out.println("Start static sleep");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("End static sleep");
}
static void staticSleepNoSyn() {
System.out.println("Start static NoSyn sleep");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("End static NoSyn sleep");
}
}
public class X {
public static void main(String[] args) {
for (int i = 0; i < 2; ++i) {
new Thread(new Runnable() {
public void run() {
Y.staticSleep();
}
}).start();
}
for (int i = 0; i < 10; ++i) {
new Thread(new Runnable() {
public void run() {
Y.staticSleepNoSyn();
}
}).start();
}
}
}
the output:
Start static sleep
Start static NoSyn sleep
Start static NoSyn sleep
Start static NoSyn sleep
Start static NoSyn sleep
Start static NoSyn sleep
Start static NoSyn sleep
Start static NoSyn sleep
Start static NoSyn sleep
Start static NoSyn sleep
Start static NoSyn sleep
End static sleep
Start static sleep
End static NoSyn sleep
End static NoSyn sleep
End static NoSyn sleep
End static NoSyn sleep
End static NoSyn sleep
End static NoSyn sleep
End static NoSyn sleep
End static NoSyn sleep
End static NoSyn sleep
End static NoSyn sleep
End static sleep