I have executed below piece of code expecting getting count as 20000. I have declared count as volatile, but the output is not proper all the time.
package threading;
public class Demo5 {
    private volatile int count =0;
    public static void main(String[] args){
        Demo5 d = new Demo5();
        d.doWork();
    }
    public void doWork(){
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                for(int i=0; i<10000; i++){
                    count++;
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                for(int i=0; i<10000; i++){
                    count++;
                }
            }
        });
        t1.start();
        t2.start();
        try{
            t1.join();
            t2.join();
        }
        catch (InterruptedException  e) {
            e.printStackTrace();
        }
        System.out.println(count+" is count");
    }
}
Later I tried making count as synchronized by putting it inside a synchronized method, and it was working properly.
public synchronized void increment(){
        count++;
    }
Can someone tell me when we should go for volatile and when for synchronized ?
 
    