多線程靜態方法同步

來源:互聯網
上載者:User

轉載▼
   


public class StaticSynTest extends Thread {
 StaticMothod sm;
 public StaticSynTest(StaticMothod sm){
  this.sm = sm;
 }
 public static void main(String[] args) {
  StaticMothod sm1 = new StaticMothod();
  StaticSynTest sst1 = new StaticSynTest(sm1);
  StaticSynTest sst2 = new StaticSynTest(sm1);
  StaticSynTest sst3 = new StaticSynTest(sm1);
  sst1.setName("sst1");
  sst2.setName("sst2");
  sst3.setName("sst3");
  
  sst1.start();
  sst2.start();
  sst3.start();
 }
 
 public void run(){
  this.sm.b(Thread.currentThread().getName());
  this.sm.b1(Thread.currentThread().getName());
  StaticMothod.a(Thread.currentThread().getName());
  StaticMothod.a1(Thread.currentThread().getName());
  
 }
}
class StaticMothod{
 public synchronized static void a(String name){
  System.out.println(name+":a in");
  try{
   Thread.sleep(2000);
   System.out.println("");
  }
  catch(InterruptedException e){
   
  }
  System.out.println(name+":a out");
 }
 public synchronized static void a1(String name){
  System.out.println(name+":a1 in");
  try{
   Thread.sleep(2000);
   System.out.println("");
  }
  catch(InterruptedException e){
   
  }
  System.out.println(name+":a1 out");
 }
 public synchronized void b(String name){
  System.out.println(name+":b in");
  try{
   Thread.sleep(2000);
   System.out.println("");
  }
  catch(InterruptedException e){
   
  }
  System.out.println(name+":b out");
 }
 public synchronized void b1(String name){
  System.out.println(name+":b1 in");
  try{
   Thread.sleep(2000);
   System.out.println("");
  }
  catch(InterruptedException e){
   
  }
  System.out.println(name+":b1 out");
 }
}

輸出結果為:

sst1:b in
 
sst1:b out
sst2:b in
 
sst2:b out
sst3:b in
 
sst3:b out
sst1:b1 in
 
sst1:b1 out
sst1:a in
sst2:b1 in
 
sst1:a out
sst1:a1 in
 
sst2:b1 out
sst3:b1 in
 
sst3:b1 out
 
sst1:a1 out
sst2:a in
 
sst2:a out
sst3:a in
 
sst3:a out
sst2:a1 in
 
sst2:a1 out
sst3:a1 in
 
sst3:a1 out

 

結論:

1、當前線程調用類的同步靜態方法時,其它線程可以進入該類執行個體的其它非靜態方法,不能進入類的其它靜態方法。

2、同理,當前進入同步的執行個體方法時,其它線程可以進入該類的靜態方法,但是不能進入該類的其它非靜態方法。

原因:靜態方法同步是擷取StaticSynTest.class鎖,而執行個體方法擷取的是該“執行個體對象”的鎖,它們互不干涉。

聯繫我們

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