使用volatile的例子



package com.my;

class MultiThreadingExample implements Runnable {

    private volatile int testValue;

    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                System.out.println(Thread.currentThread().getName() + ": " + i);

                if (Thread.currentThread().getName().equalsIgnoreCase("T1")) {
                    testValue = 10+i;
                }
                if (Thread.currentThread().getName().equalsIgnoreCase("T2")) {
                    System.out.println("Test value: " + testValue);
                }

                Thread.sleep(30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

public class VolatileExample {

    /**
     * @param args
     */
    public static void main(String[] args) {

        MultiThreadingExample volatileExample = new MultiThreadingExample();

        Thread t1 = new Thread(volatileExample, "T1");
        Thread t2 = new Thread(volatileExample, "T2");

        t1.start();
        t2.start();

    }
}

未使用volatile修飾testValue後的運行結果:

T1: 0
T2: 0
Test value: 10
T1: 1
T2: 1
Test value: 11
T2: 2
T1: 2
Test value: 11
T2: 3
Test value: 12
T1: 3
T2: 4
T1: 4
Test value: 13

由於testValue的值保存在緩存(CPU的寄存器)中,導致線程2讀取的值與線程1寫入的值不同,從而產生紅色部分所示的錯誤。使用了volatile修飾testValue值後,
程序運行結果就是正確的了

T1: 0
T2: 0
Test value: 10
T1: 1
T2: 1
Test value: 11
T1: 2
T2: 2
Test value: 12
T1: 3
T2: 3
Test value: 13
T1: 4
T2: 4
Test value: 14


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章