Java线程同步小陷阱,你掉进去过吗?

【问题】

当一个线程使用String常量作为信号量,来实现同步会如何?你有用过吗?

[java]  view plain copy
  1. package test.mult;  
  2.   
  3. /** 
  4.  * @ClassName: Test 
  5.  * @author whwang 
  6.  * @date 2012-1-10 下午02:28:39 
  7.  *  
  8.  */  
  9. public class Test {  
  10.   
  11.     private String mutex = "mutex";  
  12.   
  13.     public void f(String flag) {  
  14.     System.out.println(flag + ", entry mehtod f");  
  15.     synchronized (mutex) {  
  16.         System.err.println(flag + ", invoke method f....");  
  17.         try {  
  18.         Thread.sleep(10 * 1000);  
  19.         } catch (InterruptedException e) {  
  20.         e.printStackTrace();  
  21.         }  
  22.     }  
  23.     }  
  24.   
  25.     public static void main(String[] args) {  
  26.     // t1  
  27.     Test t1 = new Test();  
  28.     MyThread thread1 = new MyThread();  
  29.     MyThread thread2 = new MyThread();  
  30.     thread1.test = t1;  
  31.     thread2.test = t1;  
  32.   
  33.     // t2  
  34.     Test t2 = new Test();  
  35.     MyThread thread3 = new MyThread();  
  36.     MyThread thread4 = new MyThread();  
  37.     thread3.test = t2;  
  38.     thread4.test = t2;  
  39.   
  40.     thread1.start();  
  41.     thread2.start();  
  42.     thread3.start();  
  43.     thread4.start();  
  44.     }  
  45. }  
  46.   
  47. class MyThread extends Thread {  
  48.   
  49.     Test test;  
  50.   
  51.     @Override  
  52.     public void run() {  
  53.     while (true) {  
  54.         this.test.f(this.toString());  
  55.     }  
  56.     }  
  57.   
  58. }  
上面这段代码,本来应该是要实现线程thread1和thread2同步,线程thread3和thread4同步的,但结果呢?

却是使得线程thread1、thread2、thread3、thread4同步了,囧。

导致这结果的理由很简单:由于常量池的原因,所有值为“mutex”的字符串常量,都指向了同一个对象。


这让我想起了原来看过的另一篇关于StringBuilder的文章:

[java]  view plain copy
  1. int value = 100;  
  2. StringBuilder sb = new StringBuilder(value);  
作者的本意是,构造一个StringBuilder对象,初始值为“100”,但实际却是开辟了一个长度为value的char数组,如果这个value再大点。。。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值