Here I have three simple classes:
Grade 1:
public class ThreadSyncMain { public static int count = 0;
Grade 2:
public class Thread1 implements Runnable{ public void run() { System.out.println("Thread1 Count :: "+ThreadSyncMain.count); ThreadSyncMain.count++; } }
Grade 3:
public class Thread2 implements Runnable{ public void run() { System.out.println("Thread2 Count :: "+ThreadSyncMain.count); } }
Output:
Thread1 Count :: 0
Thread2 Count :: 1
This means that thread1 has changed the value of count. So why does a change in thread1 affect thread2 since I am not using any kind of "mutable" keyword. Is the βerraticβ keyword not an issue in this scenario? How can I change the code to check volatile?
Thanks in advance.
Update part: I update the code after performing trial and trial tests. Class 1 remains the same. Here is the updated code:
Class 2: I added a delay of 100 milliseconds.
public class Thread1 implements Runnable{ public void run() { System.out.println("Thread1 Count :: "+ThreadSyncMain.count); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } ThreadSyncMain.count++; } }
Class 3: added while loop. Inside his account is constantly monitored.
public class Thread2 implements Runnable{ public void run() { while(true) { if(ThreadSyncMain.count == 1) { System.out.println("Thread2 Count :: "+ThreadSyncMain.count); } } } }
Now in this situation, I got the following results:
1. If "volatile" is not used to exit class 1:
Thread1 Count :: 0
2. If the release of class1 uses "volatile":
Thread1 Count :: 0 Thread2 Count :: 1 Thread2 Count :: 1 Thread2 Count :: 1 . . .
Why does volatility appear in this scenario?
Angom source share