【問題】
當一個線程使用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) {// t1Test t1 = new Test();MyThread thread1 = new MyThread();MyThread thread2 = new MyThread();thread1.test = t1;thread2.test = t1;// t2Test 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再大點。。。。。