根據(jù)javadoc,實現(xiàn)Executor必須符合:內(nèi)存一致性效果:在將 Runnable 對象提交給 Executor 之前,線程 ( A ) 中的操作發(fā)生在其執(zhí)行開始之前,可能在另一個線程 ( B ) 中。由于我的英語很差,我不清楚B和隨后由A提交給同一個 Executor 的另一個潛在線程C之間的內(nèi)存一致性關(guān)系(如果有的話)。我希望下面的例子能澄清我的疑問。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線程執(zhí)行emc.mr2.run()?(在我的測試中這總是正確的,但是......是的,它們是測試)如果不是,官方 API 中是否有接口可以確保emc.a == 2?
1 回答
翻過高山走不出你
TA貢獻1875條經(jīng)驗 獲得超3個贊
不,不能保證,因為您emc.a在一個線程中更改值但從另一個線程提交Runnable。如果您在將第一個可運行對象設(shè)置為 2 之后從第一個可運行對象提交第二個可運行對象,則 JavaDoc 的內(nèi)存一致性效果將適用。
但是在您的示例中,即使不考慮 JavaDoc 中的注釋,volatile變量的使用也會起到作用。isDone由于您首先遞增emc.a,然后將新值設(shè)置為isDone然后檢查isDone它是否會在關(guān)系之前建立,并且第二個可運行將始終看到更新的值。
添加回答
舉報
0/150
提交
取消
