gpt4 book ai didi

java - 线程未给出正确的输出

转载 作者:行者123 更新时间:2023-12-01 23:57:55 26 4
gpt4 key购买 nike

一个使用线程的小程序确实困扰着我,有人可以解释为什么这没有给出我认为应该的输出吗?

class FirstClass {
public static void main(String args[]) {
Class2 two = new Class2();
Thread thread1 = new Thread(two);
thread1.start();

Class3 three =new Class3(two);
Thread thread2 = new Thread(three);
thread2.start();
}
}
class Class2 implements Runnable {
public Boolean variable1 = false;
@Override
public void run() {
System.out.println("Sleeping thread");
try {
Thread.sleep(3000);
}catch(Exception e){}
variable1=true;
System.out.println("Variable 1 = " + variable1);
}
}
class Class3 implements Runnable {
Class2 two;
public Class3(Class2 _two) {
this.two = _two;
}
@Override
public void run() {
while(!this.two.variable1) {
//System.out.println("in while");
}
System.out.println("Variable1 was changed to true");
}
}

上面的内容会给我正确的输出,即“ sleep 线程”、“variable1 = true”、“variable1 已更改为 true”。现在,如果我稍微更改程序并取消注释 'System.out.println("in while");'我没有得到“Variable1 已更改为 true”,就像它没有突破 while 循环,但为什么 'System.out.println("in while")' 会使其突破?或者也许它不是吗?如果有人能解释发生了什么,我将不胜感激。

谢谢

最佳答案

您正在从多个线程访问 two.variable1,而没有任何类型的同步。因此,您遇到了可见性问题:第二个线程从其内部缓存中读取变量的值,并且不知道它已被第一个线程更改。

您应该使变量 volatile ,或使用AtomicBoolean,或使用同步方法访问它,以确保对变量的写入刷新到主线程内存,变量是从主存中读取的。

调用 System.out.println() 会产生使变量可见的副作用,因为 println 方法是同步的。

关于java - 线程未给出正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15309919/

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