gpt4 book ai didi

java-为什么同步块(synchronized block)没有给出正确的循环结果

转载 作者:行者123 更新时间:2023-11-29 10:02:45 25 4
gpt4 key购买 nike

<分区>

我已经编写了一个代码来创建多个线程并启动它。我使用同步块(synchronized block)将监视器锁定在对象上。我希望创建的第一个线程应该锁定对象并完成其工作。然后任何其他物体都可以进入它。

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com