java synchronized 多線程 分析

Arnold41L 8年前發布 | 6K 次閱讀 Java開發

來自: http://blog.csdn.net//never_cxb/article/details/50378571


鎖住對象和該對象對應的類

也就是 synchronized (Sync.class) 和synchronized (this) 的區別

</blockquote>

看下面的代碼

class Sync {

public void test() {
    synchronized (this) {
        System.out.println("test開始..");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("test結束..");
    }
}

}

class MyThread extends Thread { private Sync s;

MyThread(Sync s) {
    this.s = s;
}

public void run() {
    s.test();
}

}

public class aa {

public static void main(String[] args) {

    for (int i = 0; i < 3; i++) {
        Sync sync = new Sync();
        Thread thread = new MyThread(sync);
        thread.start();
    }
}

}</pre>

注意我們在 main 里面的 for 循環每次都新建了一個新的 Sync 對象,如果是synchronized (this) ,鎖同一個對象,但是源代碼是多個對象,所以沒有鎖的效果。輸出:

test開始..
test結束..
test開始..
test結束..
test開始..
test結束..

如果把 main 函數改為如下:

public static void main(String[] args) {
    Sync sync = new Sync();
    for (int i = 0; i < 3; i++) {
        Thread thread = new MyThread(sync);
        thread.start();
    }
}

我們新建 Sync 對象放在 for 循環之外,所以只有一個 Sync 對象,被 this 鎖住,輸出是加鎖的效果

test開始..
test結束..
test開始..
test結束..
test開始..
test結束..

如果我們想對于多個 Sync 對象都加鎖,那么需要用 synchronized (Sync.class), 實現鎖這個類對應的Class對象。

public void test() {
    synchronized (Sync.class) {
        System.out.println("test開始..");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("test結束..");
    }
}

輸出結果是加鎖的效果:

test開始..
test結束..
test開始..
test結束..
test開始..
test結束..

Java線程同步:synchronized鎖住的是代碼還是對象

</div>

 本文由用戶 Arnold41L 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!