Java多線程初學者指南(6):謹慎使用volatile關鍵字

來源:互聯網
上載者:User

  volatile關鍵字相信瞭解Java多線程的讀者都很清楚它的作用。volatile關鍵字用於聲明簡單類型變數,如int、float、 boolean等資料類型。如果這些單一資料型別聲明為volatile,對它們的操作就會變成原子層級的。但這有一定的限制。例如,下面的例子中的n就 不是原子層級的:

package mythread;

public class JoinThread extends Thread
{
    public static volatile int n = 0;
    public void run()
    {
        for (int i = 0; i < 10; i++)
            try
        {
                n = n + 1;
                sleep(3); // 為了使運行結果更隨機,延遲3毫秒

            }
            catch (Exception e)
            {
            }
    }

    public static void main(String[] args) throws Exception
    {

        Thread threads[] = new Thread[100];
        for (int i = 0; i < threads.length; i++)
            // 建立100個線程
            threads[i] = new JoinThread();
        for (int i = 0; i < threads.length; i++)
            // 運行剛才建立的100個線程
            threads[i].start();
        for (int i = 0; i < threads.length; i++)
            // 100個線程都執行完後繼續
            threads[i].join();
        System.out.println("n=" + JoinThread.n);
    }
}

     如果對n的操作是原子層級的,最後輸出的結果應該為n=1000,而在執行上面積代碼時,很多時侯輸出的n都小於1000,這說明n=n+1不是原子層級 的操作。原因是聲明為volatile的簡單變數如果當前值由該變數以前的值相關,那麼volatile關鍵字不起作用,也就是說如下的運算式都不是原子 操作:

n = n + 1;
n++;

      如果要想使這種情況變成原子操作,需要使用synchronized關鍵字,如上的代碼可以改成如下的形式:

package mythread;

public class JoinThread extends Thread
{
    public static int n = 0;

    public static synchronized void inc()
    {
        n++;
    }
    public void run()
    {
        for (int i = 0; i < 10; i++)
            try
            {
                inc(); // n = n + 1 改成了 inc();
                sleep(3); // 為了使運行結果更隨機,延遲3毫秒

            }
            catch (Exception e)
            {
            }
    }

    public static void main(String[] args) throws Exception
    {

        Thread threads[] = new Thread[100];
        for (int i = 0; i < threads.length; i++)
            // 建立100個線程
            threads[i] = new JoinThread();
        for (int i = 0; i < threads.length; i++)
            // 運行剛才建立的100個線程
            threads[i].start();
        for (int i = 0; i < threads.length; i++)
            // 100個線程都執行完後繼續
            threads[i].join();
        System.out.println("n=" + JoinThread.n);
    }
}

    上面的代碼將n=n+1改成了inc(),其中inc方法使用了synchronized關鍵字進行方法同步。因此,在使用volatile關鍵字時要慎 重,並不是只要簡單類型變數使用volatile修飾,對這個變數的所有操作都是原來操作,當變數的值由自身的上一個決定時,如n=n+1、n++ 等,volatile關鍵字將失效,只有當變數的值和自身上一個值無關時對該變數的操作才是原子層級的,如n = m + 1,這個就是原層級的。所以在使用volatile關鍵時一定要謹慎,如果自己沒有把握,可以使用synchronized來代替volatile。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.