forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAtomicBooleanEx.java
More file actions
50 lines (32 loc) · 1.32 KB
/
AtomicBooleanEx.java
File metadata and controls
50 lines (32 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.zetcode;
import java.util.concurrent.atomic.AtomicBoolean;
public class AtomicBooleanEx {
public static void main(final String[] arguments) {
final AtomicBoolean atomicBoolean = new AtomicBoolean(false);
var t1 = new Thread("Thread 1") {
public void run() {
while (true) {
System.out.printf("%s Waiting for Thread 2 to set Atomic var to true %n",
Thread.currentThread().getName(), atomicBoolean.get());
if (atomicBoolean.compareAndSet(true, false)) {
System.out.println("Finished");
break;
}
}
}
};
t1.start();
var t2 = new Thread("Thread 2") {
public void run() {
System.out.printf("%s Atomic var: %s%n", Thread.currentThread().getName(),
atomicBoolean.get());
System.out.printf("%s is setting the Atomic var to true %n",
Thread.currentThread().getName());
atomicBoolean.set(true);
System.out.printf("%s Atomic var: %s%n", Thread.currentThread().getName(),
atomicBoolean.get());
}
};
t2.start();
}
}