I understood the difference between volatile and static keywords on variables.
static variables can be changed by different instances whereas Volatile variables can be changed by different threads.
But the below program(Copied from internet and little modified) hangs, if i remove the static keyword for MY_INT variable.
The update to variable MY_INT should be seen by other thread even without static key word. But if i remove static it hangs.
Please help me to understand this issue.
public class PrintOddAndEven extends Thread {
static volatile int i = 1;
Object lock;
PrintOddAndEven(Object lock) {
this.lock = lock;
}
public static void main(String ar[]) {
Object obj = new Object();
PrintOddAndEven odd = new PrintOddAndEven(obj);
PrintOddAndEven even = new PrintOddAndEven(obj);
odd.setName("Odd");
even.setName("Even");
odd.start();
even.start();
}
@Override
public void run() {
while (i <= 10) {
if (i % 2 == 0 && Thread.currentThread().getName().equals("Even")) {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + " - " + i);
i++;
lock.notify();
}
}
if (i % 2 == 1 && Thread.currentThread().getName().equals("Odd")) {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + " - " + i);
i++;
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}