0

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
3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by masijade
0

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.

Edited by masijade: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.