2013-09-22 64 views
1

我寫了一個代碼,創建了幾個線程並啓動它。我使用同步block.i鎖定對象的監視器,期望第一個創建的線程應該鎖定對象並完成其工作。那麼任何其他物體都可以進入它。java-why同步塊沒有給出正確的結果循環

但它沒有發生,程序在下面。

class ThreadCreationDemo implements Runnable 
{ 
    public void run() 
    { 
     synchronized(this) 
     { 
      for(int i=0;i<10;i++) 
      { 
       System.out.println("i: "+i+" thread: "+Thread.currentThread().getName()+" threadgroup: "+Thread.currentThread().getThreadGroup()+" "+Thread.holdsLock(this)); 
       try { 
        Thread.sleep(1000); 
       } 
       catch(Exception e) 
       { 
        System.out.println(e.toString()); 
       }   
      } 
     } 
    } 

    public static void main(String args[]) 
    { 
     Thread t[]=new Thread[5]; 

     for(int i=0;i<5;i++) 
     { 
      t[i]=new Thread(new ThreadCreationDemo()); 
      t[i].start(); 
     } 
    } 
} 

我期望的結果應該是這樣的。

第一所有對於i值= 0至9的下一個線程名印刷說線程0 那麼線程1等

但輸出是這樣的:

i: 0 thread: Thread-1 
i: 0 thread: Thread-3 
i: 0 thread: Thread-2 
i: 0 thread: Thread-0 
i: 0 thread: Thread-4 
i: 1 thread: Thread-1 
i: 1 thread: Thread-4 
i: 1 thread: Thread-3 
i: 1 thread: Thread-0 
i: 1 thread: Thread-2 
i: 2 thread: Thread-1 
i: 2 thread: Thread-3 
i: 2 thread: Thread-2 
i: 2 thread: Thread-0 
i: 2 thread: Thread-4 
i: 3 thread: Thread-1 
i: 3 thread: Thread-3 
i: 3 thread: Thread-0 
i: 3 thread: Thread-4 
i: 3 thread: Thread-2 
i: 4 thread: Thread-1 
i: 4 thread: Thread-3 
i: 4 thread: Thread-2 
i: 4 thread: Thread-4 
i: 4 thread: Thread-0 
i: 5 thread: Thread-1 
i: 5 thread: Thread-4 
i: 5 thread: Thread-3 

回答

6

問題是你每次創建一個新對象:new ThreadCreationDemo()

所以所有的線程都獲得對不同對象的鎖定,因此鎖定會失敗。

3

您在

synchronized(this) 

同步換句話說,每個實例都鎖定在本身。你沒有鎖定共享對象。

解決方案是鎖定由所有類實例共享的靜態對象。例如

synchronized (ThreadCreationDemo.class) {...} 

或者,在創建Thread時,通過在共享對象中參考其中每個Thread可以同步上。

new ThreadCreationDemo(new Object()); 
... 
public ThreadCreationDemo(Object o) { 
    this.lock = o 
} 

public void run() { 
    synchronized (lock) { 
     ... 
    } 
} 
相關問題