【问题标题】:Memory Consistency Properties explanation内存一致性属性说明
【发布时间】:2018-02-11 03:13:47
【问题描述】:

我正在查看https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html#MemoryVisibility 并且无法理解这意味着什么 - “线程中的所有操作都会发生 - 在任何其他线程从该线程的连接成功返回之前。”我能否举个例子说明这意味着什么以及示例中发生之前的保证是什么。

【问题讨论】:

  • 你到底是怎么理解的?

标签: java multithreading memory


【解决方案1】:

如果你有他下面的代码

public class Test {

 public static int i = 1;
 public static void main(String[] args) throws Exception {
  System.out.println("Start main");
  Thread t = new Thread(new Runnable() {
    public void run() {
      System.out.println("Start second");
      i = 10;
    }
  });
  t.start();
  t.join();
  System.out.println("After join");
  System.out.println(i); //should print 10
 }
}

run() 方法中完成的所有事情都发生在主线程从t.join(); 取回控制权之前。这就是为什么静态变量i 在主线程中打印时将具有值10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 2016-12-22
    相关资源
    最近更新 更多