java - invoke synchronized static method,then can other static methods be accessed? -
i have question synchronized static methods. if invoke synchronized static method, mean lock class , other method (including static or no static) can not accessed before synchronized static method end?
when synchronized static method locking class object, why other static method can invoked @ same time?
class y { static synchronized void staticsleep() { system.out.println("start static sleep"); seek { thread.sleep(2000); } grab (interruptedexception e) { } system.out.println("end static sleep"); } static void staticsleepnosyn() { system.out.println("start static nosyn sleep"); seek { thread.sleep(2000); } grab (interruptedexception e) { } system.out.println("end static nosyn sleep"); } } public class x { public static void main(string[] args) { (int = 0; < 2; ++i) { new thread(new runnable() { public void run() { y.staticsleep(); } }).start(); } (int = 0; < 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
i see asking now.
if invoke synchronized static method, mean lock class , other method (including static or no static) can not accessed before synchronized static method end?
if both methods synchronized
or utilize synchronized
block, , synchronizing on same thing (i.e. same class
or same this
, mutual exclusion.
in example, 1 method not synchronized
(and doesn't utilize synchronized
block) therefore, not locked out. in fact, nil lock out staticsleepnosyn
... have written it.
java
No comments:
Post a Comment