Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread

 
sanjana narayanan
Ranch Hand
Posts: 142
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a question on the topic 'thread' in a mock exam
public class TestClass implements Runnable
{
int x = 5;
public void run()
{
this.x = 10;
}
public static void main(String[] args)
{
TestClass tc = new TestClass();
new Thread(tc).start(); // 1
System.out.println(tc.x);
}
}
The ans given is 'output cannot be predicted'. Pl. explain to me..
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi sanjana,
We can't predict the output because we can't guarantee when the method run() will be executed (after or before System.out.println(tc.x)).
 
Vivek Nidhi
Ranch Hand
Posts: 133
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello
Invoking a start() method on a thread object, this will move the thread to the running state, this will be in a pool of threads waiting to run. Here the Thread Scheduler will select a thread in pool for running, so which Thread will be selected depends on the Thread Scheduler
So invoking a Start method on a thread only says that thread moves from new state to ready state and may move to running state.
Hope this helps
regs
Vivek Nidhi
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic