synchronized鎖住的對象能否被修改

線程1通過synchronized將obj鎖住,線程2還能否併發修改obj的內容?
代碼示例:

public class ThreadTest {
    private String name = "step1";

    public void step1(){
        synchronized (this){
            try {
                System.out.println("********t1 sleep******1 name=" + this.name);
                Thread.sleep(10000);
                System.out.println("********t1 sleep******2 name=" + this.name);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void step2(){ //synchronized保留與否有啥區別?
        this.name = "step2";
        System.out.println("********t2 update****** name=" + this.name);
    }

    public static void main(String[] args) throws Exception{
        ThreadTest threadTest = new ThreadTest();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                threadTest.step1();
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                threadTest.step2();
            }
        });

        t1.start();
        Thread.sleep(100);
        t2.start();
    }
}

運行結果:

********t1 sleep******1 name=step1
********t1 sleep******2 name=step1
********t2 update****** name=step2

如果將step2()方法的synchronized去掉,運行結果:

********t1 sleep******1 name=step1
********t2 update****** name=step2
********t1 sleep******2 name=step2

說明:即使對象監視器被鎖住,非synchronized修飾的方法依然可以修改對象監視器的值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章