954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Thread - Value

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
solomon_13000
Junior Poster in Training
88 posts since Jul 2009
Reputation Points: 24
Solved Threads: 0
 

1+10+1+10 = 22

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

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.

masijade
Industrious Poster
Moderator
4,253 posts since Feb 2006
Reputation Points: 1,471
Solved Threads: 494
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: