且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

java synchronized锁不同class的区别是什么

更新时间:2023-02-03 19:57:01

好多人说没有区别,这样吧,直接上代码和结果吧

public class Test {

    static Runnable lock = new Runnable() {
        @Override
        public void run() {
            synchronized (A.class) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    static Runnable syncA = new Runnable() {
        @Override
        public void run() {
            A.syncShowTime();
        }
    };

    static Runnable syncB = new Runnable() {
        @Override
        public void run() {
            B.syncShowTime();
        }
    };

    static Runnable lockA = new Runnable() {
        @Override
        public void run() {
            A.lockShowTime();
        }
    };

    static Runnable lockB = new Runnable() {
        @Override
        public void run() {
            B.lockShowTime();
        }
    };

    static Runnable instA = new Runnable() {
        @Override
        public void run() {
            A a = new A();
            a.instShowTime();
        }
    };

    static Runnable instB = new Runnable() {
        @Override
        public void run() {
            B b = new B();
            b.instShowTime();
        }
    };

    public static void main(String args[]) {
        try {
            new Thread(lock).start();
            Thread.sleep(1000);
            System.out.println("S:" + (int) (System.currentTimeMillis() / 1000L));
            new Thread(syncA).start();
            new Thread(syncB).start();
            new Thread(lockA).start();
            new Thread(lockB).start();
            new Thread(instA).start();
            new Thread(instB).start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class A {
    static synchronized void syncShowTime() {
        System.out.println("A sync:" + (int) (System.currentTimeMillis() / 1000L));
    }

    static void lockShowTime() {
        synchronized (A.class) {
            System.out.println("A lock:" + (int) (System.currentTimeMillis() / 1000L));
        }
    }

    void instShowTime() {
        synchronized (A.class) {
            System.out.println("A inst:" + (int) (System.currentTimeMillis() / 1000L));
        }
    }
}

class B {
    static synchronized void syncShowTime() {
        System.out.println("B sync:" + (int) (System.currentTimeMillis() / 1000L));
    }

    static void lockShowTime() {
        synchronized (B.class) {
            System.out.println("B lock:" + (int) (System.currentTimeMillis() / 1000L));
        }
    }

    void instShowTime() {
        synchronized (B.class) {
            System.out.println("B inst:" + (int) (System.currentTimeMillis() / 1000L));
        }
    }
}

S:1469596337
B sync:1469596337
B lock:1469596337
B inst:1469596337
A inst:1469596341
A lock:1469596341
A sync:1469596341