Skip to content

Commit 6de8add

Browse files
committed
多线程仅且只执行一次
1 parent 81133b2 commit 6de8add

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package multi_threads;
2+
3+
import multi_threads.atomic_start_once.RWThread;
4+
5+
import java.util.ArrayList;
6+
import java.util.List;
7+
8+
public class Test {
9+
public static void main(String[] args) {
10+
11+
List<RWThread> list = new ArrayList<>();
12+
13+
for (int i = 0; i < 20; i++) {
14+
list.add(new RWThread());
15+
}
16+
17+
for (RWThread rwThread : list) {
18+
rwThread.start();
19+
}
20+
21+
22+
for (RWThread rwThread : list) {
23+
try {
24+
rwThread.join();
25+
} catch (InterruptedException e) {
26+
e.printStackTrace();
27+
}
28+
}
29+
30+
System.out.println();
31+
System.out.println("count: " + RWThread.count);
32+
33+
34+
}
35+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package multi_threads.atomic_start_once;
2+
3+
import java.util.concurrent.atomic.AtomicBoolean;
4+
import java.util.concurrent.atomic.AtomicInteger;
5+
6+
public class RWThread extends Thread {
7+
8+
public static final AtomicBoolean ab = new AtomicBoolean(false);
9+
10+
public static final AtomicInteger count = new AtomicInteger(0);
11+
12+
13+
@Override
14+
public void run() {
15+
16+
// 多线程环境下,保证仅且只执行一次
17+
if (!ab.compareAndSet(false, true)) {
18+
return;
19+
}
20+
21+
count.incrementAndGet();
22+
}
23+
}

0 commit comments

Comments
 (0)