2013-09-22 59 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) { 
     ... 
    } 
} 
相关问题