我写了一个代码,创建了几个线程并启动它。我使用同步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