Java線程同步小陷阱,你掉進去過嗎?

來源:互聯網
上載者:User

【問題】

當一個線程使用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再大點。。。。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.