gpt4 book ai didi

java - 即使在使用 synchronized() 之后,字符串也没有按顺序显示

转载 作者:行者123 更新时间:2023-11-29 07:47:42 24 4
gpt4 key购买 nike

当我观察到这个问题时,我正试图理解同步函数。首先,这是代码 -

SampleThread04.java

public class SampleThread04 extends Thread
{
public void disp(String s)
{
System.out.print("["+s);
try
{
Thread.sleep(1000);
}catch(Exception e){
System.out.print(e);
}
System.out.println("]");
}
}

SampleThread05.java

public class SampleThread05 implements Runnable
{
SampleThread04 d;
String s;
Thread t;
public SampleThread05(SampleThread04 d1, String s1)
{
s = s1;
t = new Thread(this);
d = d1;
t.start();
}
public void run()
{
synchronized(d){
d.disp(s);
}
}
}

ThreadDemo02.java

public class ThreadDemo02
{
public static void main(String[] args)
{
SampleThread04 st4 = new SampleThread04();
new SampleThread05(st4,"one");
new SampleThread05(st4,"two");
new SampleThread05(st4,"three");
}
}

我在运行代码时得到不同的输出。

输出#1:

[one]
[two]
[three]

输出#2:

[three]
[one]
[two]

输出#3:

[three]
[two]
[one]

等等。

在不使用 synchronized() 的情况下,我得到以下输出 -

[one[two[three]
]
]

这很好理解,但为什么当我使用 synchronized() 时,字符串有时会乱序打印,而在不使用它时我总是得到相同的输出。输出不应该总是如下 -

[one]
[two]
[three]

请解释字符串是如何乱序打印的。提前致谢。 :)

最佳答案

synchronized 语句只会导致disp 方法作为一个整体执行。由于您正在为每个字符串启动一个新线程,因此您无法控制首先执行哪个线程。尽管线程按顺序启动,但它们不会按相同的顺序完成。

关于java - 即使在使用 synchronized() 之后,字符串也没有按顺序显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24033027/

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