Why is the value 22 created for the code below?

public class Pregnant extends Thread{ 
    int x = 0;
    public static void main(String[] args){
    	Runnable r1 = new Pregnant();
    	new Thread(r1).start();
    	new Thread(r1).start();
    }
    public void run(){
    	for(int j=0;j<3;j++){
    		x = x + 1;
    		x = x + 10;
    		System.out.println(x + " ");
    		x = x + 100;
    	}
    }
}

The results are as below:

11 
133 
244 
22 
455 
566

1+10+1+10 = 22

Because both threads are using the same instance of r1, and so the same "x" variable, but since nothing there is synchronized (except the println which is synched internally) the 22 came out later than you might have expected (and it might not have come out at all since you can't sure which thread will have which value, when, but you are probably on a single core machine, and the thread interlace has produced, to you, strange results) but it is the result of both threads doing x + 1 and x + 10 on the same, non-synched, variable.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.