简体   繁体   中英

invoke synchronized static method,then can other static methods be accessed?

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

I see what you are asking now.

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?

IF both methods are synchronized or use a synchronized block, AND they are synchronizing on the same thing (ie the same Class or the same this , THEN you will get mutual exclusion.

In your example, one method is not synchronized (and it doesn't use a synchronized block) so therefore, it will not be locked out. In fact, nothing will lock out staticSleepNoSyn ... as you have written it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM