• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread output doesnt make sense

 
Vinay Kumbhar
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I cannot seem to understand the output of this code. Although the output changes everytime I execute. There's one output which does not make sense.
It is :
Thread[Thread-0,5,main] 3
Thread[Thread-1,5,main] 1
main3
If Thread 1 changes the value of x to 1 then how come main thread still prints value of x as 3


 
Paul Clapham
Sheriff
Posts: 21862
36
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First line 25 evaluates "main"+x, getting "main3". Then the other two threads run and output their values. Finally line 25 gets control and calls System.out.println() to print "main3". Remember, what you see in line 25 is far from atomic.
 
Vinay Kumbhar
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, so what I gather from what you said is that evaluation and call to print function doesnt happen at the same time.
 
Paul Clapham
Sheriff
Posts: 21862
36
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. You seem to have assumed that entire lines of code are atomic, that is that they are executed all at once by a single thread without interruption. That is far from being the case. Even something as simple as x++ is not atomic; it's possible for two threads to attempt that simultaneously and end up adding only 1 instead of 2 to the variable. So atomicity is very important, and I'd recommend you go back and read your chapter on threads and synchronization looking for information about it.

And by the way, welcome to the Ranch!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!