Why do primitive variable in multithreading little program, behave as a volatile variable? Please help me in my code.
/**
* Practice with threads problem visibility.
* @author Matevosyan Vardan
* @version 1.0
* created on 21.09.2017
*/
public class VisibilityProblem {
private static int countingVal = 0;
public static int getCountingVal() {
return countingVal;
}
Start in main
public static void main(String[] args) throws InterruptedException {
Thread looperR = new VisibilityProblem.Looper();
Thread listener = new VisibilityProblem.Listener();
listener.start();
looperR.start();
listener.join();
looperR.join();
}
Class to wright and increase counting variable after sleep 500 millisecond to wait a little, what helps do some staff Listener thread.
public static class Looper extends Thread {
@Override
public void run() {
while (VisibilityProblem.countingVal < 5) {
VisibilityProblem.countingVal++;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("increase " + VisibilityProblem.countingVal);
}
}
}
Class to read and assign counting value
public static class Listener extends Thread {
@Override
public void run() {
int localCount = VisibilityProblem.countingVal;
while (localCount < 5) {
if (localCount != VisibilityProblem.countingVal) {
System.out.println("It is " + localCount + " now");
localCount = VisibilityProblem.countingVal;
}
}
}
}
}