对于线程加锁synchronized可能存在的误区的解析


使用synchronized之后,并不是说synchronized锁定的方法或者代码块要一次性执行完,才能跳转到其他线程。而是当两个并发线程访问同一个对象object中的这个synchronized(this)同步代码块时,一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。也即是说,即使给某个方法加锁了,如果其他线程访问不是这个方法时,线程依然可以跳转。如下例子:

 1 public class test2{
 2     public static void main(String[] args) {
 3         Thread a=new A2();
 4         Thread b=new B2();
 5         a.start();
 6         b.start();
 7     }
 8 }
 9 
10 class A2 extends Thread{
11     public void run(){
12         show1();
13     }
14     public synchronized void show1(){
15         for(int i=0;i<20;i++){
16             System.out.print(i);
17         }
18     }        
19 }
20 
21 class B2 extends Thread{
22     public void run(){
23         show2();
24     }
25     public synchronized void show2(){
26         for (int i = 0; i < 20; i++) {
27             System.out.print(i);
28         }
29     }
30 }

创建了两个线程,分别访问自己的加锁show方法,最终的结果不一定是两个连续的1-19,我的运行结果如下:

001122334455667788991010111112121313141415161718191516171819

所以synchronized只是对于访问同一方法的不同线程有效。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM