File tree Expand file tree Collapse file tree 2 files changed +58
-0
lines changed
java87/src/main/java/multi_threads Expand file tree Collapse file tree 2 files changed +58
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments