-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.java
54 lines (45 loc) · 1.34 KB
/
Main.java
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
51
52
53
54
package com.quickstart._volatile;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Main {
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
new Thread(r).start();
while (true) {
synchronized (Main.class) {
// The synchronized block ensures that the reading of the flag variable
// happens with a happens-before relationship, providing visibility guarantees.
// This forces the main thread to see the most recent change made to the flag variable
// by any other thread (in this case, the thread running MyRunnable).
if (r.isFlag()) {
log.info("Main thread is over");
break;
}
}
}
}
}
@Slf4j
class MyRunnable implements Runnable {
// The volatile keyword could have fixed the issue but it is omitted here.
// The synchronized block in the main method ensures visibility of changes
// to this flag variable across threads.
private boolean flag = false;
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("Thread interrupted", e);
}
setFlag(true);
log.info("Flag set to: {}", flag);
}
}