1. 程式人生 > >synchronized(this/object/類.class)的區別

synchronized(this/object/類.class)的區別

synchronized this object Class的區別

首先放上結論:

1.this:相當於只有一把鑰匙的多把鎖,他可以鎖住多個程式碼塊,但是每次開鎖只能一個,如果鑰匙在其他程式碼塊手上,那麼新來的被鎖的多個程式碼塊就拿不到鑰匙,進不了方自己的程式碼塊

2.object:每一個object相當於一把鎖,那麼不同的鎖會有不同的鑰匙,這樣如果自己的鎖不同,一樣的鎖沒有被其他人佔據,自己開始能進入程式碼塊

3.類.clss:這是靜態的鎖,應為靜態就帶有this的含義,所以不能用this,而用類.class

下面是程式碼

Main方法–其中執行緒使用lambda表示式
public class Mian {
    public static void main(String[] args) {
        Material m = new Material();
        new Thread(()->{
            m.doSome();
        }){

        }.start();


        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                m.deOther();

            }
        })
; t2.start(); } }
object
class Material{
    private int data1=1;
    private int data2=2;
    private Object lock1 =new Object();
    private Object lock2 =new Object();
    public void doSome() {
        synchronized (lock1) {
            try {
                System.out.println(++data1);
                Thread.sleep(2000
); }catch(Exception e) { e.printStackTrace(); } } } public void deOther() { synchronized (lock2) { System.out.println(data1); } } } /*----------------- 結果: 1 2//中間沒有時間間隔 ------------------*/
this
class Material{
    private int data1=1;
    private int data2=2;
    private Object lock1 =new Object();
    private Object lock2 =new Object();
    public void doSome() {
        synchronized (this) {
            try {
                System.out.println(++data1);
                Thread.sleep(2000);
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void deOther() {
        synchronized (this) {
            System.out.println(data1);
        }

    }
}


/*-----------------
結果:
1
2//中間時間間隔2秒
------------------*/
class
class Material{
    private static int data1=1;
    private int data2=2;
    private Object lock1 =new Object();
    private Object lock2 =new Object();
    public static void doSome() {
        synchronized (Material.class) {
            try {
                System.out.println(data1);
                Thread.sleep(2000);
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void deOther() {
        synchronized (this) {
            System.out.println(data1);
        }

    }
}
/*---------------
輸出;
1
2//中間沒有時間間隔
---------------*/