类锁与对象锁实例

public class Radio {

    public static synchronized void classLock() {
        String name = Thread.currentThread().getName();
        System.out.println("classLock begin, " + name);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("classLock end, " + name);
    }

    public synchronized void instanceLock() {
        String name = Thread.currentThread().getName();
        System.out.println(">>>>>instanceLock begin, " + name);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(">>>>>instanceLock end, " + name);
    }

    public static void main(String[] args) {
        new Thread(() -> {
            Radio.classLock();
        }, "c1").start();
        new Thread(() -> {
            new Radio().classLock();
        }, "c2").start();
        new Thread(() -> {
            new Radio().classLock();
        }, "c3").start();

        Radio r = new Radio();
        new Thread(() -> {
            r.instanceLock();
        }, "i1").start();
        new Thread(() -> {
            r.instanceLock();
        }, "i2").start();

        new Thread(() -> {
            new Radio().instanceLock();
        }, "i3").start();
    }
}

上图的执行过程:

c1、c2、c3之间是互斥的。说明类锁不管是对象调用(相同的对象还是不同的对象)还是类名调用,都是互斥的。

i1与i3是并发的,  i1与i2是互斥的。说明对象锁只作用于相同对象。

i1、i3与c1是并发的。说明对象锁的获取与类锁的获取是不影响的,可以并发。

猜你喜欢

转载自www.cnblogs.com/shuada/p/9919690.html