【转】Java线程同步:synchronized是锁住对象还是锁代码(二)

上一篇 / 下一篇  2017-06-08 09:45:06 / 个人分类:Java

。 

解决也很简单,只要锁住同一个对象不就行了。例如,synchronized后的括号中锁同一个固定对象,这样就行了。这样是没问题,但是,比较多的做法是让synchronized锁这个类对应的Class对象。

[java] view plain copy
  1. class Sync {  
  2.   
  3.     public void test() {  
  4.         synchronized (Sync.class) {  
  5.             System.out.println("test开始..");  
  6.             try {  
  7.                 Thread.sleep(1000);  
  8.             } catch (InterruptedException e) {  
  9.                 e.printStackTrace();  
  10.             }  
  11.             System.out.println("test结束..");  
  12.         }  
  13.     }  
  14. }  
  15.   
  16. class MyThread extends Thread {  
  17.   
  18.     public void run() {  
  19.         Sync sync = new Sync();  
  20.         sync.test();  
  21.     }  
  22. }  
  23.   
  24. public class Main {  
  25.   
  26.     public static void main(String[] args) {  
  27.         for (int i = 0; i < 3; i++) {  
  28.             Thread thread = new MyThread();  
  29.             thread.start();  
  30.         }  
  31.     }  
  32. }  

运行结果:
test开始..
test结束..
test开始..
test结束..
test开始..
test结束..

上面代码用synchronized(Sync.class)实现了全局锁的效果

最后说说static synchronized方法,static方法可以直接类名加方法名调用,方法中无法使用this,所以它锁的不是this,而是类的Class对象,所以,static synchronized方法也相当于全局锁,相当于锁住了代码段。

 



TAG: java Java

 

评分:0

我来说两句

Open Toolbar