java synchronized代碼塊

synchronized代碼塊爲一段代碼加鎖。

在Thread多線程的實現內synchronized的鎖對象需要時各個線程都可以訪問得到的對象,如類的static變量。如果synchronized使用的鎖是對象自己所擁有的,則起不到互斥的效果。

    private static int index=0;
    private String string = new String("dfd");//無法達到互斥的效果
    @Override
    public void run() {
        // TODO Auto-generated method stub
        synchronized(string){
            for(int i=0 ;i<100;i++){
                System.out.println(getName()+" "+index++);
            }
        }

    }

        Thread thread1 = new TestSync();
        Thread thread2 = new TestSync();
        Thread thread3 = new TestSync();
        thread1.start();
        thread2.start();
        thread3.start(); 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章