开发者

Class A has 2 synch methods in Java, Class B has two static synch methods, Are 2 threads allowed to access these two scenarios

开发者 https://www.devze.com 2023-03-15 06:23 出处:网络
public class ThreadTest { public static synchronized void m2() { System.out.println(\"static sync m2\");
public class ThreadTest {
     public static synchronized void m2() {
         System.out.println("static sync m2");
         System.out.println("current"+Thread.currentThread());
         try { Thread.sleep(2000开发者_Python百科); }
         catch (InterruptedException ie) {}
     }

    public static void main(String[] args) throws InterruptedException {
        Thread t3 = new Thread() {
            public void run() {
                ThreadTest.m2();
            }
        };
        t3.start();
        t3.sleep(2000);
        Thread.sleep(500); // which thread are we sleeping here?
        System.out.println("t3.getState"+t3.getState());
    }
}

If we create another thread t1 and access ThreadTest.m2(); inside of this? yes this will be allowed, why this is static and it class level. But if we have non-static methods, then Thread 1 and 2 are not allowed to access the method


Please check this out: Java synchronized static methods: lock on object or class

Regards.

Edit: in particular, this answer: Java synchronized static methods: lock on object or class

0

精彩评论

暂无评论...
验证码 换一张
取 消