Java synchronized(class)深度解析__Java

來源:互聯網
上載者:User

同步測試代碼:

package com.zhiwei.thread;public class ThreadSynchronizedClass {    public static int sum = 0;    public void add() throws InterruptedException {        synchronized (ThreadSynchronizedClass.class) {            Thread.sleep(500);            sum++;            System.out.println(Thread.currentThread().getName() + ":add:" + sum);        }    }    public void del() throws InterruptedException {        synchronized (ThreadSynchronizedClass.class) {            Thread.sleep(500);            sum--;            System.out.println(Thread.currentThread().getName() + ":del:" + sum);        }    }    /** static將synAdd作為類自身成員,所有執行個體共用,synchronized就能保證每個執行個體訪問同步 */    public synchronized static void synAdd() throws InterruptedException {        Thread.sleep(500);        sum++;        System.out.println(Thread.currentThread().getName() + ":synAdd:" + sum);    }    public synchronized static void synDel() throws InterruptedException {        Thread.sleep(500);        sum--;        System.out.println(Thread.currentThread().getName() + ":synDel:" + sum);    }    /**     * 如果訪問外部的靜態變數一樣具有同步的效果     * @param name     * @throws InterruptedException     */    public void show(String name) throws InterruptedException {        synchronized (ThreadSynchronizedClass.class) {            Thread.sleep(500);            for (int i = 0; i < name.length(); i++) {                System.out.println(Thread.currentThread().getName() + ":" + name.charAt(i));            }        }    }    public static void main(String[] args) {        ThreadSynchronizedClass threadSynchronizedClass1 = new ThreadSynchronizedClass();        ThreadSynchronizedClass threadSynchronizedClass2 = new ThreadSynchronizedClass();        for (int i = 0; i < 20; i++) {            new Thread(new Runnable() {                @SuppressWarnings("static-access")                @Override                public void run() {                    try {                        threadSynchronizedClass1.synAdd();                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            }).start();            new Thread(new Runnable() {                @SuppressWarnings("static-access")                @Override                public void run() {                    try {                        threadSynchronizedClass2.synDel();                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            }).start();            new Thread(new Runnable() {                @Override                public void run() {                    try {                        threadSynchronizedClass2.show("abcdefghijklmn");                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            }).start();            new Thread(new Runnable() {                @Override                public void run() {                    try {                        threadSynchronizedClass1.show("abcdefghijklmn");                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            }).start();        }    }}
效果

結論:

static synchronized method等價於synchronized(class)內部訪問靜態成員變數,因為static修飾的對象成員時從屬於類本身,儲存於JVM的方法區中,所有的對象執行個體都會引用方法區中同一份Class對象,因此鎖定Class能夠達到同步的效果

探索:如果將sum設定為非靜態屬性,效果如何呢。
測試代碼:

package com.zhiwei.thread;/** * 鎖定位元組碼Class: * 1.synchronized(class)同步代碼塊在訪問外部靜態成員變數具有同步效果,非靜態成員變數不具有同步效果 * 2.static synchronized method等價於synchronized(class)內部訪問靜態成員變數 * 3.synchronized(class)同步代碼塊訪問局部變數具有同步的效果 */public class ThreadSynchronizedClass {    public  int sum = 0;    public void add() throws InterruptedException {        synchronized (ThreadSynchronizedClass.class) {            Thread.sleep(500);            sum++;            System.out.println(Thread.currentThread().getName() + ":add:" + sum);        }    }    public void del() throws InterruptedException {        synchronized (ThreadSynchronizedClass.class) {            Thread.sleep(500);            sum--;            System.out.println(Thread.currentThread().getName() + ":del:" + sum);        }    }    public static void main(String[] args) {        ThreadSynchronizedClass threadSynchronizedClass1 = new ThreadSynchronizedClass();        ThreadSynchronizedClass threadSynchronizedClass2 = new ThreadSynchronizedClass();            new Thread(new Runnable() {                @Override                public void run() {                    try {                        while(true)                        threadSynchronizedClass1.add();                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            }).start();            new Thread(new Runnable() {                @Override                public void run() {                    try {                        while(true)                        threadSynchronizedClass2.del();                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            }).start();    }}
效果:

分析:

從控制台日誌來說不同的對象執行個體並未達到同步的效果,因此可以得出一個階段syschronized(class)只對static的成員屬性能夠起到同步的作用

深度分析:synchrozized(class)雖然給類的位元組碼上鎖,但是因為sum是非靜態屬性,當類執行個體化時sum並不會儲存在方法區中,而是儲存在JVM Heap中,sum從屬於類執行個體,因此當兩個對象訪問類定義的同步方法時並不會達到同步的效果,個人認為JVM具備某種檢查機制,當使用synchronized(class)進行同步時,會檢查內部是否有共用資源,如果不存在共用資源那麼同步失效,static修飾的sum從屬於類本身,所有類執行個體共用因此能夠達到同步的效果,而非static的sum從屬於類執行個體本身,不是共用資源,因此達不到同步效果

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.