第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Executor 工作線程的 Java 內(nèi)存一致性

Executor 工作線程的 Java 內(nèi)存一致性

茅侃侃 2022-05-25 16:18:26
根據(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)系之前建立,并且第二個可運行將始終看到更新的值。


查看完整回答
反對 回復 2022-05-25
  • 1 回答
  • 0 關(guān)注
  • 87 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號