【问题标题】:Java memory consistency for Executor's worker threadsExecutor 工作线程的 Java 内存一致性
【发布时间】:2019-01-29 17:40:10
【问题描述】:

根据javadoc,Executor 的实现必须符合:

内存一致性效果:线程 (A) 中的操作在将 Runnable 对象提交给 Executor 之前发生 - 在其执行开始之前,可能在另一个线程中 (B )。

由于我的英语很差,我不清楚 B 和随后提交的另一个潜在线程 C 之间的内存一致性关系是否得到保证(如果有的话)由 A 到同一个 Executor。我希望下面的例子能澄清我的疑问。

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

class ExecutorTestClass {

    int a = 1;
    volatile boolean isDone = false;
    MyRunnable mr1 = new MyRunnable("One");
    MyRunnable mr2 = new MyRunnable("Two");

    class MyRunnable implements Runnable {
    private final String name;

    MyRunnable(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println(name + ": " + ExecutorTestClass.this.a++);
        isDone = true; // signal that addition has been performed
        while (true) {
        try {
            Thread.sleep(5); // busy thread
        } catch (InterruptedException e) {
        }
        }
    }

    }

    public static void main(String[] args) {
    ExecutorTestClass emc = new ExecutorTestClass();
    Executor executor = Executors.newFixedThreadPool(2);
    executor.execute(emc.mr1); // run the first MyRunnable
    while (!emc.isDone) {
    } // when stop spinning emc.a == 2 for this thread
    executor.execute(emc.mr2); // is emc.a == 2 guaranteed?

    }

}

是否保证emc.a == 2 用于执行emc.mr2.run() 的线程? (在我的测试中这总是正确的,但是......是的,它们是测试) 如果没有,官方API中是否有接口保证emc.a == 2?

【问题讨论】:

    标签: java multithreading memory executor happens-before


    【解决方案1】:

    不,不能保证,因为您在一个线程中更改了emc.a 的值,但从另一个线程提交了Runnable。如果您在将第一个可运行对象的值设置为 2 之后从第一个可运行对象提交第二个可运行对象,则将适用 JavaDoc 的内存一致性效果。

    但在您的示例中使用 volatile 变量 isDone 即使不考虑 JavaDoc 中的注释也可以解决问题。 由于您首先增加emc.a,然后将新值设置为isDone,然后检查isDone,它仍然会建立发生在关系,第二个可运行对象将始终看到更新的值。

    【讨论】:

      猜你喜欢
      • 2020-06-05
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-16
      • 2011-02-28
      • 1970-01-01
      相关资源
      最近更新 更多