今天打了打代碼研究了一下java的volatile關鍵字到底能不能保證線程安全,經過實踐,volatile是不能保證線程安全的,它只是保證了數據的可見性,不會再緩存,每個線程都是從主存中讀到的數據,而不是從緩存中讀取的數據,附上代碼如下,當synchronized去掉的時候,每個線程的結果是亂的,加上的時候結果才是正確的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
/** * * 類簡要描述 * * < p > * 類詳細描述 * </ p > * * @author think * */ public class VolatileThread implements Runnable { private volatile int a = 0; @Override public void run() { // TODO Auto-generated method stub // synchronized (this) { a = a + 1; System.out.println(Thread.currentThread().getName() + ":----" + a); try { Thread.sleep(100); a = a + 2; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":----" + a); // } } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
/** * * 類簡要描述 * * < p > * 類詳細描述 * </ p > * * @author think * */ public class VolatileMain { public static void main(String[] args) { VolatileThread s = new VolatileThread(); Thread t1 = new Thread(s); Thread t2 = new Thread(s); Thread t3 = new Thread(s); Thread t4 = new Thread(s); t1.start(); t2.start(); t3.start(); t4.start(); /* 同步的結果 Thread-2:----1 Thread-2:----3 Thread-0:----4 Thread-0:----6 Thread-3:----7 Thread-3:----9 Thread-1:----10 Thread-1:----12*/ /* 去掉同步的結果 Thread-0:----1 Thread-1:----2 Thread-2:----3 Thread-3:----4 Thread-0:----8 Thread-3:----10 Thread-1:----10 Thread-2:----12*/ } } |
以上這篇java中volatile不能保證線程安全(實例講解)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/Think-007/p/7084375.html