【问题标题】:Unexpected behavior while running the code and debugging [duplicate]运行代码和调试时出现意外行为[重复]
【发布时间】:2019-12-01 08:04:18
【问题描述】:

调试结果为 77777,否则为 97777。 如果我们在打印 co.code 时将 System.out.println(Thread.currentThread().getName()); 上下移动,则行为相同。 有什么解释吗?

public class Concepts extends Thread {
int code = 9;

public void run() {
    this.code = 7;
}

public static void main(String[] args) {

    Concepts co = new Concepts();
    co.start();
    for (int i = 0; i < 5; i++) {
        System.out.print(co.code + "==");
        System.out.println(Thread.currentThread().getName());
    }
  }
}

【问题讨论】:

标签: java multithreading core


【解决方案1】:

您正在执行第二个线程,它将 code 实例变量设置为 7 而不进行任何同步。

然后您从主线程访问code 变量,同样没有任何同步。

这意味着主线程可能会在另一个线程将其设置为7 之前看到code 变量的状态(这意味着它会打印9,直到它观察到另一个线程所做的更改) ,或者它可能不会(这意味着它只会打印7s)。这完全取决于哪个线程将首先运行。

如果没有同步,您就没有理由期望一种结果优于另一种。

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多