Am writing sample app to understand volatile behavior.
According to me the value of this variable should change to 50
but the output I'm getting is 10
.
Main method:
public class Volatile {
public static void main(String[] args) {
ShareObj so = new ShareObj();
Thread1 t1 = new Thread1(so);
Thread2 t2 = new Thread2(so);
t1.start();
t2.start();
System.out.println(so.a);
}
}
Classes:
class ShareObj {
public volatile int a =10;
}
class Thread1 extends Thread {
ShareObj so;
Thread1(ShareObj so) {
this.so = so;
}
public void run() {
so.a += 10;
System.out.println(so.a);
}
}
class Thread2 extends Thread {
ShareObj so;
Thread2(ShareObj so) {
this.so=so;
}
public void run() {
so.a+=10;
System.out.println(so.a);
}
}
The output I'm expecting is 50
but it is 10
.
Any suggestions?