【问题】
当一个线程使用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再大点。。。。。