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。