Skip to content

Commit d1234bc

Browse files
committed
feat: concurrency example
1 parent e693730 commit d1234bc

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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 numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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+
}

0 commit comments

Comments
 (0)