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


synchronized 修飾在 static方法和非static方法的區別

 

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

  看代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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();
     }
}

  運行結果是:

1
2
3
4
5
6
function running...
Static function running...
function running...
Static function running...
function running...
Static function running...

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

不忘初心,方得始終


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM