Threads question ocpjp.v7.2.1730
Posted: Fri Aug 22, 2014 9:22 am
Why this question the answer is
Am not understanding the explanation properly i think that because of join finally it will increment by 5000 and then decrement by 5000 after all so the answer is 0 or some one please explain to me slowley thanks
the explanation isIt may print any number between -5000 to 5000.
Making variable counter volatile only ensures that if it is updated by one thread, another thread will see the updated value. However, it still does not ensure that the increment and decrement operations will be done atomically. Thus, it is possible that while one thread is performing counter++, another thread corrupts the value by doing counter--. Because of this corruption, it is not possible to determine the final value of counter.
Am not understanding the explanation properly i think that because of join finally it will increment by 5000 and then decrement by 5000 after all so the answer is 0 or some one please explain to me slowley thanks
Code: Select all
public class RunTest {
public static volatile int counter = 0;
static class RunnerDec implements Runnable{
public void run(){
for(int i=0;i<5000; i++){
counter--; }
}
}
static class RunnerInc implements Runnable{
public void run(){
for(int i=0;i<5000; i++){
counter++; }
}
}
public static void main(String[] args) {
RunnerDec rd = new RunnerDec();
RunnerInc ri = new RunnerInc();
Thread t1 = new Thread(rd);
Thread t2 = new Thread(ri);
t1.start();
t2.start();
try{
t1.join();
t2.join();
}catch(Exception e){
e.printStackTrace();
}
System.out.println(counter);
}
}