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

【问题】

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

package test.mult; /** * @ClassName: Test * @author whwang * @date 2012-1-10 下午02:28:39 * */ public class Test { private String mutex = "mutex"; public void f(String flag) { System.out.println(flag + ", entry mehtod f"); synchronized (mutex) { System.err.println(flag + ", invoke method f...."); try { Thread.sleep(10 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { // t1 Test t1 = new Test(); MyThread thread1 = new MyThread(); MyThread thread2 = new MyThread(); thread1.test = t1; thread2.test = t1; // t2 Test t2 = new Test(); MyThread thread3 = new MyThread(); MyThread thread4 = new MyThread(); thread3.test = t2; thread4.test = t2; thread1.start(); thread2.start(); thread3.start(); thread4.start(); } } class MyThread extends Thread { Test test; @Override public void run() { while (true) { this.test.f(this.toString()); } } } 上面这段代码,本来应该是要实现线程thread1和thread2同步,线程thread3和thread4同步的,但结果呢?

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

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


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

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值