初學(xué)Java多線程:慎重使用volatile關(guān)鍵字
volatile關(guān)鍵字相信了解Java多線程的讀者都很清楚它的作用。volatile關(guān)鍵字用于聲明簡(jiǎn)單類型變量,如int、float、boolean等數(shù)據(jù)類型。如果這些簡(jiǎn)單數(shù)據(jù)類型聲明為volatile,對(duì)它們的操作就會(huì)變成原子級(jí)別的。但這有一定的限制。例如,下面的例子中的n就不是原子級(jí)別的:
- 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); // 為了使運(yùn)行結(jié)果更隨機(jī),延遲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個(gè)線程
- threads[i] = new JoinThread();
- for (int i = 0; i < threads.length; i++)
- // 運(yùn)行剛才建立的100個(gè)線程
- threads[i].start();
- for (int i = 0; i < threads.length; i++)
- // 100個(gè)線程都執(zhí)行完后繼續(xù)
- threads[i].join();
- System.out.println("n=" + JoinThread.n);
- }
- }
如果對(duì)n的操作是原子級(jí)別的,***輸出的結(jié)果應(yīng)該為n=1000,而在執(zhí)行上面積代碼時(shí),很多時(shí)侯輸出的n都小于1000,這說(shuō)明n=n+1不是原子級(jí)別的操作。原因是聲明為volatile的簡(jiǎn)單變量如果當(dāng)前值由該變量以前的值相關(guān),那么volatile關(guān)鍵字不起作用,也就是說(shuō)如下的表達(dá)式都不是原子操作:
n = n + 1;
n++;
如果要想使這種情況變成原子操作,需要使用synchronized關(guān)鍵字,如上的代碼可以改成如下的形式:
- 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); // 為了使運(yùn)行結(jié)果更隨機(jī),延遲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個(gè)線程
- threads[i] = new JoinThread();
- for (int i = 0; i < threads.length; i++)
- // 運(yùn)行剛才建立的100個(gè)線程
- threads[i].start();
- for (int i = 0; i < threads.length; i++)
- // 100個(gè)線程都執(zhí)行完后繼續(xù)
- threads[i].join();
- System.out.println("n=" + JoinThread.n);
- }
- }
上面的代碼將n=n+1改成了inc(),其中inc方法使用了synchronized關(guān)鍵字進(jìn)行方法同步。因此,在使用volatile關(guān)鍵字時(shí)要慎重,并不是只要簡(jiǎn)單類型變量使用volatile修飾,對(duì)這個(gè)變量的所有操作都是原來(lái)操作,當(dāng)變量的值由自身的上一個(gè)決定時(shí),如n=n+1、n++等,volatile關(guān)鍵字將失效,只有當(dāng)變量的值和自身上一個(gè)值無(wú)關(guān)時(shí)對(duì)該變量的操作才是原子級(jí)別的,如n = m + 1,這個(gè)就是原級(jí)別的。所以在使用volatile關(guān)鍵時(shí)一定要謹(jǐn)慎,如果自己沒(méi)有把握,可以使用synchronized來(lái)代替volatile。
【編輯推薦】