根据javadoc,实现Executor必须符合:
内存一致性效果:在将 Runnable 对象提交给 Executor 之前,线程 ( A ) 中的操作发生在其执行开始之前,可能在另一个线程 ( B ) 中。
由于我的英语很差,我不清楚B和随后由A提交给同一个 Executor 的另一个潜在线程C之间的内存一致性关系(如果有的话)。我希望下面的例子能澄清我的疑问。
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?
翻过高山走不出你
相关分类