1. 程式人生 > >14、synchronized程式碼塊間的同步性

14、synchronized程式碼塊間的同步性

導語:我們在使用synchronized(this)同步程式碼塊的時候需要注意:當一個執行緒訪問object物件的一個synchronized(this)同步程式碼塊的時候,其他執行緒對該object物件中的其他synchronized(this)同步程式碼塊的訪問將會是阻塞的。synchronized(this)使用的“物件監視器”是一個。

案例:

package com.demo16;

import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;

public class MyObject {
    public void a(){
        try {
            synchronized (this) {
                System.out.println("a begin time : " + System.currentTimeMillis());
                Thread.sleep(2000);
                System.out.println("a end time : " + System.currentTimeMillis());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void b(){
        synchronized (this) {
            System.out.println("b begin time : " + System.currentTimeMillis());
            System.out.println("b end time : " + System.currentTimeMillis());
        }
    }
}
package com.demo16;

public class ThreadA extends Thread{
    private MyObject myObject;

    public ThreadA(MyObject myObject) {
        this.myObject = myObject;
    }

    @Override
    public void run(){
        myObject.a();
    }
}
package com.demo16;

public class ThreadB extends Thread {
    private MyObject myObject;

    public  ThreadB(MyObject myObject){
        this.myObject = myObject;
    }

    @Override
    public void run(){
        myObject.b();
    }
}
package com.demo16;

public class Run {
    public static void main(String[] args) {
        MyObject myObject = new MyObject();
        ThreadA threadA = new ThreadA(myObject);
        ThreadB threadB = new ThreadB(myObject);
        threadA.start();
        threadB.start();
    }
}

執行結果:

a begin time : 1544792680664
a end time : 1544792682665
b begin time : 1544792682665
b end time : 1544792682665

通過結果可以將上述導語結論給驗證!