The volatile variable in Java has the effect of informing the change of its value to different threads if the variable is being used in multiple threads. For you to understand more, I made an example as follows:
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
|
public class VolatileExample { private volatile static int COUNT = 0; public static void main(String[] args) { new ChangeListener().start(); new ChangeMaker().start(); } static class ChangeListener extends Thread { @Override public void run() { int value = COUNT; // When value of COUNT variable is less than 5, this thread will loop forever to check the value of this variable while (value < 5) { if (value != COUNT) { System.out.println("Count variable changed to : " + COUNT); value = COUNT; } } } } static class ChangeMaker extends Thread { @Override public void run() { int value = COUNT; while (COUNT < 5) { System.out.println("Increasing value of count variable to " + (value + 1)); COUNT = ++value; try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } } } |
In this example, we have two… Read More