Java中synchronized用在靜態方法和非靜態方法上面的區別

來源:互聯網
上載者:User

標籤:add   val   border   number   rup   ber   order   cin   擷取   

  在Java中,synchronized是用來表示同步的,我們可以synchronized來修飾一個方法。也可以synchronized來修飾方法裡面的一個語句塊。那麼,在static方法和非static方法前面加synchronized到底有什麼不同呢?大家都知道,static的方法屬於類方法,它屬於這個Class(注意:這裡的Class不是指Class的某個具體對象),那麼static擷取到的鎖,是屬於類的鎖。而非static方法擷取到的鎖,是屬於當前對象的鎖。所以,他們之間不會產生互斥。

  看代碼:

1234567891011121314151617181920212223242526272829303132333435363738394041424344 public class Demo {    public static synchronized void staticFunction()            throws InterruptedException {        for (int i = 0; i < 3; i++) {            Thread.sleep(1000);            System.out.println("Static function running...");        }    }     public synchronized void function() throws InterruptedException {        for (int i = 0; i <3; i++) {            Thread.sleep(1000);            System.out.println("function running...");        }    }     public static void main(String[] args) {        final Demo demo = new Demo();        Thread thread1 = new Thread(new Runnable() {            @Override            public void run() {                try {                    staticFunction();                catch (InterruptedException e) {                    e.printStackTrace();                }            }        });         Thread thread2 = new Thread(new Runnable() {            @Override            public void run() {                try {                    demo.function();                catch (InterruptedException e) {                    e.printStackTrace();                }            }        });         thread1.start();        thread2.start();    }}

  運行結果是:

123456 function running...Static function running...function running...Static function running...function running...Static function running...

  那當我們想讓所有這個類下面的方法都同步的時候,也就是讓所有這個類下面的靜態方法和非靜態方法共用同一把鎖的時候,我們如何辦呢?此時我們可以使用Lock。

Java中synchronized用在靜態方法和非靜態方法上面的區別

聯繫我們

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