The question says that what is the oputput of this program
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); } a) 5 b) 10 c) will not compile d) Exception at run time e) output cannot be determined JQ+ says the answer is e . i thought the answer will be 10 but when i ran the program the answer was 5. i am sooooo confused can someone help me please
Valentin Crettaz
Gold Digger
Sheriff
Joined: Aug 26, 2001
Posts: 7610
posted
0
The thing is that start() hands over the job of scheduling the thread to the scheduler and returns immediately and println() is invoked just after it. So there are 2 possibilities: - either the thread has been started, in which case 10 is printed - or the thread hasn't been started yet and 5 is printed You cannot predict the output in such cases...
I got a 5 when i ran the program and everytime i run the program [ February 27, 2002: Message edited by: Tosin Adedoyin ]
Rodney Woodruff
Ranch Hand
Joined: Dec 04, 2001
Posts: 80
posted
0
You have to keep in mind that the thread scheduler is platform dependent. Therefore, the thread scheduler could start before you get to the println, but it really depends on the platform.
If and only if there is threadObject.join(); before System.out.println(tc.x) you can definitely say that the output will be 10, otherwise output can not be determined, because you never know when the Thread will be scheduled. HTH, - Manish
Duncan Allen
Greenhorn
Joined: Jan 15, 2002
Posts: 19
posted
0
Hey Tosin, This is one of those questions that will appear in your studies and may appear in the exam that you cannot answer by just running the code. Unlike normal methods (where the code waits for the called method to return) the run() method (when called from the start()) runs in its own "thread". So in your case there are two sections of code running at one time. hence why you cant predict the ouput Hope that helps note: lookout for questions that directly call the run() method, these WILL NOT run in a separate thread, but will wait for the method to return