|
3 | 3 | public class TaskRunner {
|
4 | 4 | /**
|
5 | 5 | * 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. |
6 | 11 | */
|
7 | 12 | private static int number;
|
8 |
| - private static boolean ready; |
| 13 | + private volatile static boolean ready; |
9 | 14 |
|
10 | 15 | private static class Reader extends Thread {
|
11 | 16 | @Override
|
12 | 17 | public void run() {
|
13 |
| - System.out.println("ready is: " + ready); |
| 18 | + System.out.println(Thread.currentThread().getName() + " thread says, ready = " + ready); |
14 | 19 | while (!ready) {
|
15 |
| - System.out.println("It's yielding now.."); |
| 20 | + System.out.println(Thread.currentThread().getName() + " is yielding now.."); |
16 | 21 | Thread.yield();
|
17 | 22 | }
|
18 |
| - System.out.println("number is: " + number); |
| 23 | + System.out.println(Thread.currentThread().getName() + " thread says, number = " + number); |
19 | 24 | }
|
20 | 25 | }
|
21 | 26 |
|
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..."); |
24 | 29 | new Reader().start();
|
| 30 | + System.out.println(Thread.currentThread().getName() + " thread is running now..."); |
25 | 31 | number = 42;
|
| 32 | + Thread.sleep(6); |
| 33 | + System.out.println(Thread.currentThread().getName() + " thread finishes sleeping."); |
26 | 34 | ready = true;
|
27 |
| - System.out.println("Program finished."); |
| 35 | + System.out.println(Thread.currentThread().getName() + " thread finished."); |
28 | 36 | }
|
29 | 37 | }
|
0 commit comments