• Post Reply Bookmark Topic Watch Topic
  • New Topic

WHY This Thread gives me this?  RSS feed

 
Brian Smith
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi folks,
why am i having so much difficulty in what's going on here with thread? i have the following codes and printing some other than i expect. could you please explain me in layman's way?

why does it print 7 instead of 17?
thanks.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At the time the System.out.println(t.x) the new assignment wasn't yet
executed. This is why you get 7 and not 17. Maybe 10ms later there would be 17. You cannot know when the system executes the x=17;
Olli
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Timing issues; there's no garuntee when the run method will actually be called. So, when you print out the result, the run method has not actually happened yet. If you put in a

You will see the result of 17, since this gives the run method time to execute.
In your example, I would like to say that you will always see 7, but I can't make that broad of a statement. I will say that, due to the overhead in setting up the separate thread, you will be likely to always see 7; however, sometimes the thread might get set up and run before the call to that println happens, so you would see 17. This is unlikely, however, due to the aforementioned overhead involved in setting up the separate thread.
 
Brian Smith
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it looks that there are two Threads in the above program. because when the start() method gets invoked, it spawns a new thread and right after that the main thead return and starts executing the lines of codes after start() method. this executiong happens much earlier than the new thread created by start() gets chance to invoke run() and set the value of x. But if we have main thread sleep(1000) then the new thread created by invoking start() method gets to invoke run() and sets value of x to 17 so that when the sleep time elapses, the new value of x e.i. 17 gets printed.
could you please verify what i have just said?
thanks.
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that adequately sums up what is happening.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!