-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVolatileTest.java
More file actions
84 lines (76 loc) · 2.14 KB
/
Copy pathVolatileTest.java
File metadata and controls
84 lines (76 loc) · 2.14 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.demo.java.multi_thread;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @Author: zjhan
* @Date: 2021/5/24 17:38
* @Description: 关键字volatile使用例子
**/
public class VolatileTest {
public volatile int inc = 0;
public Lock lock = new ReentrantLock();
/**
* 因为
*/
public void increase() {
inc++;
}
public void increaseWithLock() {
lock.lock();
inc ++;
lock.unlock();
}
/**
* 执行结束后结果不一定是10000,因为 #increase方法不具有原子性
* @param test
*/
public static void multiThread(VolatileTest test) {
for(int i=0;i<10;i++){
new Thread(){
public void run() {
for(int j=0;j<1000;j++)
test.increase();
};
}.start();
}
}
/**
* 执行结果为10000,因为使用了锁,锁内的操作为原子操作
* @param test
*/
public static void multiThreadWithLock(VolatileTest test) {
for(int i=0;i<10;i++){
new Thread(){
public void run() {
for(int j=0;j<1000;j++)
test.increaseWithLock();
};
}.start();
}
}
/**
* 执行结果为10000,因为使用了锁,锁内的操作为原子操作
* @param test
*/
public static void multiThreadWithSynchronized(VolatileTest test) {
for(int i=0;i<10;i++){
new Thread(){
public void run() {
for(int j=0;j<1000;j++)
synchronized (this) {
test.increaseWithLock();
}
};
}.start();
}
}
public static void main(String[] args) {
final VolatileTest test = new VolatileTest();
// multiThread(test);
// multiThreadWithLock(test);
multiThreadWithSynchronized(test);
while(Thread.activeCount()>1)
Thread.yield();
System.out.println(test.inc);
}
}