類鎖與對象鎖實例

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();
    }
}

上圖的執行過程:併發

c一、c二、c3之間是互斥的。說明類鎖不論是對象調用(相同的對象仍是不一樣的對象)仍是類名調用,都是互斥的。spa

i1與i3是併發的,  i1與i2是互斥的。說明對象鎖只做用於相同對象。code

i一、i3與c1是併發的。說明對象鎖的獲取與類鎖的獲取是不影響的,能夠併發。對象

相關文章
相關標籤/搜索