This question already has an answer here:
Statement execution interleaving with Synchronized method execution
                                
                                    (1个答案)
                                
                        
                                6年前关闭。
            
                    
我已经编写了创建几个线程并启动它的代码。我使用同步块将监视器锁定在对象上。我希望创建的第一个线程应锁定对象并完成其工作。那么其他任何对象都可以输入它。

但它没有发生,程序在下面。

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

最佳答案

问题是您每次都在创建新对象:new ThreadCreationDemo()

因此,所有线程都获得对不同对象的锁定,因此锁定将失败。

07-26 03:27