java 類鎖與對象鎖(執行個體鎖)同步問題

來源:互聯網
上載者:User

標籤:pre   catch   star   sleep   override   代碼   exce   多線程   int   

眾所周知,synchronized可修飾方法和代碼塊,可作用於類或者對象。

當修飾代碼塊時,synchronized(object) 作用於對象,只約束該對象。

 synchronized(class)作用於類,約束類所有的對象。

修飾方法時,synchronized 修飾static方法時,作用於類。修飾非static方法時作用於對象。

注意類鎖和對象鎖是兩個不同的鎖,二者不會發生同步關係。

由於static變數,可被static方法調用,也可被非static方法調用,當二者同時被synchronized修飾時,所以就會出現潛在的同步問題。

所以多線程時靜態變數盡量只用靜態方法調用,不然就會出現同步混亂。

 

class Test implements Runnable{    public  static  int num = 0;    public synchronized void changeNum(){        num++;        System.out.println(num);    }      public synchronized static void addNum(){        num++;        System.out.println(num);    }    @Override    public void run() {        for (int i = 0; i < 2000; i++) {            changeNum();            addNum();            try {                Thread.sleep(5);            }catch (InterruptedException ie){            }        }    }    public static void main(String[] args) {         Test test = new Test();        Thread t1 = new Thread(test);        Thread t2 = new Thread(test);        t1.start();        t2.start();    }}

如果同步,結果應該是8000,然而並不是。

 

java 類鎖與對象鎖(執行個體鎖)同步問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.