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是并发的。说明对象锁的获取与类锁的获取是不影响的,可以并发。

 

相关文章:

  • 2021-11-20
  • 2021-08-27
  • 2021-08-21
  • 2022-12-23
  • 2021-10-24
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-09-11
  • 2021-10-16
  • 2021-12-12
  • 2022-12-23
  • 2021-11-16
相关资源
相似解决方案