溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

volatile關(guān)鍵字的作用以及對變量的影響

發(fā)布時間:2020-06-08 16:33:50 來源:億速云 閱讀:313 作者:Leah 欄目:編程語言

這篇文章主要為大家分享volatile關(guān)鍵字對普通全局變量的效果影響。其次介紹了volatile關(guān)鍵字的作用,閱讀完整文相信大家對volatile關(guān)鍵字了一定的認(rèn)識。

接下來,我們就一起來分析下這個問題!讓我們先通過一個例子來回顧下volatile關(guān)鍵字的作用!

public class VolatitleFoo {
    //類變量
    final static int max = 5;
    static int init_value = 0;

    public static void main(String args[]) {
        //啟動一個線程,當(dāng)發(fā)現(xiàn)local_value與init_value不同時,則輸出init_value被修改的值
        new Thread(() -> {
            int localValue = init_value;
            while (localValue < max) {
                if (init_value != localValue) {
                    System.out.printf("The init_value is update ot [%d]\n", init_value);
                    //對localValue進(jìn)行重新賦值
                    localValue = init_value;
                }
            }
        }, "Reader").start();
        //啟動updater線程,主要用于對init_value的修改,當(dāng)local_value=5的時候退出生命周期
        new Thread(() -> {
            int localValue = init_value;
            while (localValue < max) {
                //修改init_value
                System.out.printf("The init_value will be changed to [%d]\n", ++localValue);
                init_value = localValue;
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Updater").start();
    }
}

在上面的代碼示例中,我們定義了兩個類變量max、init_value,然后在主線程中分別啟動一個Reader線程,一個Updater線程。Updater線程做的事情就是在值小于max的值時以每兩毫秒的速度進(jìn)行自增。而Reader線程則是在感知init_value值發(fā)生變化的情況下進(jìn)行讀取操作。

期望的效果是線程Updater更新init_value值之后,可以立刻被線程Reader感知到,從而進(jìn)行輸出顯示。實際運行效果如下:

The init_value will be changed to [1]
The init_value will be changed to [2]
The init_value will be changed to [3]
The init_value will be changed to [4]
The init_value will be changed to [5]

實際的運行效果是在Updater修改類變量init_value后,Reader線程并沒有立馬感知到變化,所以沒有進(jìn)行相應(yīng)的顯示輸出。而原因就在于共享類變量init_value在被線程Updater拷貝到該線程的工作內(nèi)存中后,Updater對變量init_value的修改都是在工作內(nèi)存中進(jìn)行的,完成操作后沒有立刻同步回主內(nèi)存,所以Reader線程對其改變并不可見。

為了解決線程間對類變量init_value的可見性問題,我們將類變量init_value用volatile關(guān)鍵字進(jìn)行下修飾,如下:

static volatile int init_value = 0;

然后我們再運行下代碼,看看結(jié)果:

The init_value will be changed to [1]
The init_value is update ot [1]
The init_value will be changed to [2]
The init_value is update ot [2]
The init_value will be changed to [3]
The init_value is update ot [3]
The init_value will be changed to [4]
The init_value is update ot [4]
The init_value will be changed to [5]
The init_value is update ot [5]

此時線程Updater對類變量init_value的修改,立馬就能被Reader線程感知到了,這就是volatile關(guān)鍵字的效果,可以讓共享變量在線程間實現(xiàn)可見,原因就在于在JVM的語義層面要求被volatile修飾的共享變量,在工作內(nèi)存中的修改要立刻同步回主內(nèi)存,并且讀取也需要每次都重新從主內(nèi)存中刷新一份到工作內(nèi)存中后才可以操作。

關(guān)于以上適用volatile關(guān)鍵字修飾基本類型的類變量、實例變量的場景,相信大家會比較好理解。接下來,我們來繼續(xù)改造下代碼:

public class VolatileEntity {
    //使用volatile修飾共享資源i
    //類變量
    final static int max = 5;
    int init_value = 0;
    public static int getMax() {
        return max;
    }
    public int getInit_value() {
        return init_value;
    }
    public void setInit_value(int init_value) {
        this.init_value = init_value;
    }
    private static class VolatileEntityHolder {
        private static VolatileEntity instance = new VolatileEntity();
    }
    public static VolatileEntity getInstance() {
        return VolatileEntityHolder.instance;
    }
}

我們將之前代碼中的類變量init_value放到實體類VolatileEntity中,并將其設(shè)計為一個實例變量,為了便于理解,我們將實體類VolatileEntity設(shè)計為單例模式,確保兩個線程操作的是同一個共享堆內(nèi)存對象。如下:

public class VolatileEntityTest {

    //使用volatile修飾共享資源
    private static VolatileEntity volatileEntity = VolatileEntity.getInstance();

    private static final CountDownLatch latch = new CountDownLatch(10);

    public static void main(String args[]) throws InterruptedException {
        //啟動一個線程,當(dāng)發(fā)現(xiàn)local_value與init_value不同時,則輸出init_value被修改的值
        new Thread(() -> {
            int localValue = volatileEntity.init_value;
            while (localValue < VolatileEntity.max) {
                if (volatileEntity.init_value != localValue) {
                    System.out.printf("The init_value is update ot [%d]\n", volatileEntity.init_value);
                    //對localValue進(jìn)行重新賦值
                    localValue = volatileEntity.init_value;
                }
            }
        }, "Reader").start();

        //啟動updater線程,主要用于對init_value的修改,當(dāng)local_value=5的時候退出生命周期
        new Thread(() -> {
            int localValue = volatileEntity.init_value;
            while (localValue < VolatileEntity.max) {
                //修改init_value
                System.out.printf("The init_value will be changed to [%d]\n", ++localValue);
                volatileEntity.init_value = localValue;
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Updater").start();
    }
}

在上述代碼中線程Updater和Reader此時操作的是類變量VolatileEntity對象中的普通實例變量init_value。在VolatileEntity對象沒被volatile關(guān)鍵字修飾之前,我們看下運行效果:

The init_value will be changed to [1]
The init_value will be changed to [2]
The init_value will be changed to [3]
The init_value will be changed to [4]
The init_value will be changed to [5]

與未被volatile修飾的int類型的類變量效果一樣,線程Updater對VolatileEntity對象中init_value變量的操作也不能立馬被線程Reader可見。如果此時我們不VolatileEntity類中單獨用volatile關(guān)鍵字修飾init_value變量,而是直接VolatileEntity對象用volatile關(guān)鍵字修飾,效果會如何呢?

private static volatile VolatileEntity volatileEntity = VolatileEntity.getInstance();

此時VolatileEntity對象的引用變量被volatile關(guān)鍵字修飾了,然而其中的普通實例變量init_value并沒有直接被volatile關(guān)鍵字修飾,然后我們在運行下代碼看看效果:

The init_value will be changed to [1]
The init_value is update ot [1]
The init_value will be changed to [2]
The init_value is update ot [2]
The init_value will be changed to [3]
The init_value is update ot [3]
The init_value will be changed to [4]
The init_value is update ot [4]
The init_value will be changed to [5]
The init_value is update ot [5]

從實際的運行效果上看,雖然我們沒有直接用volatile關(guān)鍵字修飾對象中的類變量init_value,而是修改了對象的引用,但是我們看到對象中的普通實例變量仍然實行了線程間的可見性,也就是說間接也相當(dāng)于被volatile關(guān)鍵字修飾了。所以,在這里問題也就基本上有了答案,那就是:“被volatile關(guān)鍵字修飾的對象作為類變量或?qū)嵗兞繒r,其對象中攜帶的類變量和實例變量也相當(dāng)于被volatile關(guān)鍵字修飾了”。

看完上述內(nèi)容,你們對volatile關(guān)鍵字有進(jìn)一步的了解嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI