File tree 2 files changed +60
-0
lines changed
src/com/fghpdf/Concurrency
2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .fghpdf .Concurrency ;
2
+
3
+ /**
4
+ * @author fghpdf
5
+ * @date 2019/11/16
6
+ **/
7
+ public class VolatileAtomic {
8
+ private static volatile int num = 0 ;
9
+
10
+ private static void atom () {
11
+ num ++;
12
+ }
13
+
14
+ public static void main (String [] args ) throws InterruptedException {
15
+ Thread [] threads = new Thread [10 ];
16
+
17
+ for (int i = 0 ; i < threads .length ; i ++) {
18
+ threads [i ] = new Thread (() -> {
19
+ for (int j = 0 ; j < 1000 ; j ++) {
20
+ atom ();
21
+ }
22
+ });
23
+ threads [i ].start ();
24
+ }
25
+
26
+ for (Thread t : threads ) {
27
+ t .join ();
28
+ }
29
+
30
+ System .out .println (num );
31
+ }
32
+ }
Original file line number Diff line number Diff line change
1
+ package com .fghpdf .Concurrency ;
2
+
3
+ /**
4
+ * @author fghpdf
5
+ * @date 2019/11/16
6
+ **/
7
+ public class VolatileVisibility {
8
+ // volatile
9
+ private static volatile boolean initFlag = false ;
10
+
11
+ public static void main (String [] args ) throws InterruptedException {
12
+ new Thread (() -> {
13
+ System .out .println ("waiting data ..." );
14
+ while (!initFlag ) {
15
+
16
+ }
17
+ System .out .println ("done" );
18
+ }).start ();
19
+
20
+ Thread .sleep (2000 );
21
+
22
+ new Thread (() -> {
23
+ System .out .println ("change data" );
24
+ initFlag = true ;
25
+ System .out .println ("changed" );
26
+ }).start ();
27
+ }
28
+ }
You can’t perform that action at this time.
0 commit comments