-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAtomictyIntegerTest.java
More file actions
58 lines (51 loc) · 1.45 KB
/
AtomictyIntegerTest.java
File metadata and controls
58 lines (51 loc) · 1.45 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
package Thread.Basic;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jdt.internal.compiler.ast.ThisReference;
/*
* 用原子类改装之前的AtomictyTest类,可以不用synchronize和volatile来保证执行的正确性
*
* 原子类:诸如AtomicInteger AtomicDouble AtomicReference
*
* Atomic类被设计用来构建java.util.concurrent包中的类,只有在特殊情况下才在自己的类中使用它,通常依赖锁来解决(synchronize,Lock)
*
* */
public class AtomictyIntegerTest implements Runnable{
private AtomicInteger i=new AtomicInteger(0);
public int getValue(){
return i.get();
}
public void increment(){
i.addAndGet(2);
}
@Override
public void run() {
while(true){
increment();
}
}
public static void main(String[] args) {
//程序运行时正确的,用一个定时任务来控制5秒后停止
new Timer().schedule(new TimerTask() {
@Override
public void run() {
System.err.println("Aborting");
System.exit(0);
}
}, 5000);
ExecutorService executorService=Executors.newCachedThreadPool();
AtomictyIntegerTest test=new AtomictyIntegerTest();
executorService.execute(test);
while(true){
int val=test.getValue();
System.out.println(val);
if(val%2!=0){
System.out.println(val);
System.exit(0);
}
}
}
}