Synchronized關(guān)鍵字

Synchronized 關(guān)鍵字一般在 多線程訪問(wèn)同一代碼塊時(shí) 保證這段代碼執(zhí)行的原子性。
有以下幾個(gè)方面需要注意下

1, synchronized 鎖的有哪些?

① 對(duì)象(臨界資源對(duì)象,比如 Object o = new Object() 的o 就是臨界資源對(duì)象)
② this (調(diào)用當(dāng)前方法的對(duì)象 )
3 類(lèi)對(duì)象(也就相當(dāng)于 比如Test.class 這樣的 ,一般是有static修飾的)
下面是一段示例代碼:

public class TestSync {
    
    private int count = 0;
    private static int staticCount = 0;
    private Object object = new Object();
    private static Object staticObject = new Object();
    
    /**
     * 1, testSync1和testSync2 這種形式的 也成為 鎖的是代碼塊,而testSync3鎖的是整個(gè)方法
     * 2, 鎖this 和 鎖method 差不多
     */
    
    public void testSync1() {
        synchronized (object) { //鎖的是臨界資源對(duì)象 object
            System.out.println(Thread.currentThread().getName()+" count "+ count++);
        }
    }
    
    //鎖的是this,也就是調(diào)用當(dāng)前方法的對(duì)象 比如 TestSync t = new TestSync(); t.testSync2();  這個(gè)t
    public void testSync2() {
        synchronized (this) { 
            System.out.println(Thread.currentThread().getName()+" count "+ count++);
        }
    }
    
    // 鎖的是方法 , 這個(gè)級(jí)別較重, 一般不建議使用
    public synchronized void testSync3() { 
        System.out.println(Thread.currentThread().getName()+" count "+ count++);
        
    }
    
    //這種鎖的 是 TestSync.class
    public static synchronized void testSync4() {
        System.out.println(Thread.currentThread().getName()+" staticCount "+ staticCount++);
    }
    
    public static  void testSync5() {
        synchronized (staticObject) {
            System.out.println(Thread.currentThread().getName()+" staticCount "+ staticCount++);
        }
    }
}

2,同步方法 只保證當(dāng)前方法的原子性,不保證多個(gè)業(yè)務(wù)方法之間的互相訪問(wèn)的原子性

看一段示例代碼

public class TestSync {
    private int i = 0;
    public void set(int i) {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.i = i;
    }
    
    public int get() {
        return this.i;
    }
    
    //運(yùn)行后 先后顯示 0  100
    public static void main(String[] args) {
        TestSync t = new TestSync();
        new Thread(new Runnable() {
            @Override
            public void run() {
                t.set(100);
            }
        }).start();
        System.out.println(t.get());  //這里為0
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(t.get()); //這里為100
    }
}

3 鎖的重入

條件:
① 同一個(gè)線程 ②多次調(diào)用同步代碼 3 鎖定同一個(gè)對(duì)象

下面看一個(gè)段代碼

public class TestSync { 
    synchronized void m1(){ // 鎖this
        System.out.println("m1 start");
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        m2();
        System.out.println("m1 end");
    }
    synchronized void m2(){ // 鎖this
        System.out.println("m2 start");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("m2 end");
    }
    
    public static void main(String[] args) {
        
        //先后打印如下 m1 start,m2 start,m2 end,m1 end
        new TestSync().m1(); //同一個(gè)線程 多次調(diào)用同步代碼(這里為m1() 和 m2() ), 鎖定的都是this
        
    }
}

當(dāng)然注意一個(gè)點(diǎn) : 子類(lèi)同步方法 覆蓋 父類(lèi)同步方法,可以指定調(diào)用父類(lèi)的同步方法,這種相當(dāng)于鎖的重入

示例代碼:

public class TestSync { 
    synchronized void m(){
        System.out.println("Super Class m start");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Super Class m end");
    }
    
    public static void main(String[] args) {
        //這里依次打印Sub Class m start,Super Class m start,Super Class m end,Sub Class m end
        new SubTestSync().m();
    }
}
class SubTestSync extends TestSync{ //繼承父類(lèi)
    synchronized void m(){ //重寫(xiě)父類(lèi)同步方法
        System.out.println("Sub Class m start");
        super.m();
        System.out.println("Sub Class m end");
    }
}

4 鎖與異常

當(dāng)同步方法發(fā)生異常的時(shí)候,自動(dòng)釋放鎖資源,不會(huì)影響其他線程的執(zhí)行
比如當(dāng) i/0 時(shí) 發(fā)生異常了,程序會(huì)自動(dòng)朝后執(zhí)行

5 在定義同步代碼時(shí),不要使用常量作為鎖對(duì)象

public class TestSync {
    String s1 = "hello";
    String s2 = "hello"; // new String("hello");
    Integer i1 = 1;
    Integer i2 = 2;

    void m1() {
        synchronized (s1) { // 可換成 i1
            System.out.println("m1()");
            while (true) {

            }
        }
    }

    void m2() {
        synchronized (s2) { // 換成 i2
            System.out.println("m2()");
            while (true) {

            }
        }
    }

    public static void main(String[] args) {
        final TestSync t = new TestSync();

        new Thread(new Runnable() {
            @Override
            public void run() {
                t.m1();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                t.m2();
            }
        }).start();

        // 運(yùn)行時(shí) 可以發(fā)現(xiàn) 只有m1() 打印出來(lái)了,m2() 一直不打印,,如果 s2 = new String("hello"); 則可以打印
        // Integer 的值在 -128~127之間的數(shù)字 只打印m1()

        // 常量所為鎖對(duì)象會(huì)出現(xiàn)問(wèn)題
    }
}

6 鎖對(duì)象變更問(wèn)題

同步代碼一旦加鎖后,那么會(huì)有一個(gè)臨時(shí)的鎖引用執(zhí)行鎖對(duì)象,和真實(shí)的引用無(wú)直接關(guān)聯(lián)。
在鎖未釋放之前,修改鎖對(duì)象引用,不會(huì)影響同步代碼的執(zhí)行。

public class TestSync {
    void m() {
        System.out.println(Thread.currentThread().getName() + " start");
        synchronized (o) {
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " - " + o);
            }
        }
    }

    public static void main(String[] args) {
        final TestSync t = new TestSync();
        new Thread(new Runnable() {
            @Override
            public void run() {
                t.m();
            }
        }, "thread1").start();
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                t.m();
            }
        }, "thread2");
        t.o = new Object(); // 這個(gè) 改變了
        thread2.start();

    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容