8000 update TaskRunner · fishercoder1534/RandomJava@9ad20f8 · GitHub
[go: up one dir, main page]

Skip to content

Commit 9ad20f8

Browse files
update TaskRunner
1 parent 916b49f commit 9ad20f8

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

src/main/java/java_volatile/TaskRunner.java

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,27 +3,35 @@
33
public class TaskRunner {
44
/**
55
* This is following the examples from https://www.baeldung.com/java-volatile
6+
*
7+
* Volatile keyword is to deal with Java Memory Model cache coherent challenges:
8+
* To ensure that updates to variables propagate predictably to other threads, we should apply the volatile modifier to those variables.
9+
* This way, we can communicate with runtime and processor to not reorder any instruction involving the volatile variable.
10+
* Also, processors understand that they should immediately flush any updates to these variables so that other threads could read the shared variables most up-to-date values.
611
*/
712
private static int number;
8-
private static boolean ready;
13+
private volatile static boolean ready;
914

1015
private static class Reader extends Thread {
1116
@Override
1217
public void run() {
13-
System.out.println("ready is: " + ready);
18+
System.out.println(Thread.currentThread().getName() + " thread says, ready = " + ready);
1419
while (!ready) {
15-
System.out.println("It's yielding now..");
20+
System.out.println(Thread.currentThread().getName() + " is yielding now..");
1621
Thread.yield();
1722
}
18-
System.out.println("number is: " + number);
23+
System.out.println(Thread.currentThread().getName() + " thread says, number = " + number);
1924
}
2025
}
2126

22-
public static void main(String[] args) {
23-
System.out.println("Program started.");
27+
public static void main(String[] args) throws InterruptedException {
28+
System.out.println(Thread.currentThread().getName() + " thread started now...");
2429
new Reader().start();
30+
System.out.println(Thread.currentThread().getName() + " thread is running now...");
2531
number = 42;
32+
Thread.sleep(6);
33+
System.out.println(Thread.currentThread().getName() + " thread finishes sleeping.");
2634
ready = true;
27-
System.out.println("Program finished.");
35+
System.out.println(Thread.currentThread().getName() + " thread finished.");
2836
}
2937
}

0 commit comments

Comments
 (0)
0