12
12
13
13
public class Chp_2_3_6_AtomicIntegerUnSafeTest {
14
14
15
- protected class MyService {
16
- // 此处如果修改为
17
- // static AtomicLong aiRef = new AtomicLong(0L);
18
- // 可以保持原子性和方法调用均保持有序输出
19
-
20
- private AtomicLong aiRef = new AtomicLong (0L );
21
-
22
- public long getValue () {
23
- return aiRef .get ();
24
- }
25
-
26
- synchronized public void addNum () {
27
- System .out .println ("threadName=" +Thread .currentThread ().getName ()
28
- + " add 100 return value=" + aiRef .addAndGet (100 ));
29
-
30
- aiRef .addAndGet (1 );
31
- }
32
- }
33
-
34
15
protected class MyThread extends Thread {
35
- private MyService service ;
16
+ private Chp_2_3_6_AtomicIntegerService service ;
36
17
37
- public MyThread (MyService service ) {
18
+ public MyThread (Chp_2_3_6_AtomicIntegerService service ) {
38
19
super ();
39
20
this .service = service ;
40
21
}
@@ -44,24 +25,25 @@ public void run() {
44
25
service .addNum ();
45
26
}
46
27
}
47
-
28
+
48
29
// threadName=Thread-2 add 100 return value=200
49
30
// threadName=Thread-4 add 100 return value=500
50
31
// threadName=Thread-3 add 100 return value=300
51
32
// threadName=Thread-0 add 100 return value=100
52
33
// threadName=Thread-1 add 100 return value=400
53
34
// last value print in main=505
54
-
35
+
55
36
public static void main (String [] args ) {
56
37
try {
57
38
Chp_2_3_6_AtomicIntegerUnSafeTest test = new Chp_2_3_6_AtomicIntegerUnSafeTest ();
58
- MyService service = test . new MyService ();
39
+ Chp_2_3_6_AtomicIntegerService service = new Chp_2_3_6_AtomicIntegerService ();
59
40
Thread [] threads = new Thread [5 ];
60
-
61
- for (int i =0 ;i <threads .length ;i ++){
62
- threads [i ] = test .new MyThread (service );
41
+
42
+ for (int i = 0 ; i < threads .length ; i ++) {
43
+ threads [i ] = test .new MyThread (service );
44
+ threads [i ].setName ("thread-[" + (i + 1 ) + "]" );
63
45
}
64
-
46
+
65
47
for (int j = 0 ; j < threads .length ; j ++) {
66
48
threads [j ].start ();
67
49
}
@@ -72,7 +54,7 @@ public static void main(String[] args) {
72
54
} catch (InterruptedException e ) {
73
55
e .printStackTrace ();
74
56
}
75
-
57
+
76
58
}
77
59
78
60
}
0 commit comments