我寫了一個代碼,創建了幾個線程並啓動它。我使用同步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