• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Thread question......

 
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Options :
1)5
2)10
3)It will not compile
4)Exception at Runtime
5)The output cannot be determined
Answer : 1) 5
I feel that the answer should be 10 because when in the main we are starting the thead and then when the run method is called , at that time the value of x is 10.
Please explain.
Sonir
 
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sonir:
Your program is one thread,which assigns the value to x.
When you create a new instance of thread and call it's start method, that starts a new thread. The run() method gets executed by this new thread.
If the new thread is gets to execute before the println statement, then the value of x will be 10.
If the new thread has not had a chance to run, then the values of x will be 5.
Based only on this code, we can not know whether or not the new thread will start running immediately and finish before the println statement is executed. It depends on the operating system and how it implements thread scheduling, and other threads running at the same time as this program etc.
Therefore it is not possible to say what value of x will be printed .
HTH
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic