The following is a question from Whizlabs
SCJP 1.4 mock
test:
What will happen when you attempt to compile and run the following code:
class MyThread extends Thread{
public void run(){System.out.println("MyThread: run()");}
public void start(){System.out.println("MyThread: start()");}
}
class MyRunnable implements Runnable{
public void run(){System.out.println("MyRunnable: run()");}
public void start(){System.out.println("MyRunnable: start()");}
}
public class MyTest{
public static void main(
String[] args){
MyThread myThread = new MyThread();
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
myThread.start();
thread.start();
}
}
Whizlabs answer:
Prints: "MyThread: start() followed by MyRunnable:run()"
I thought the answer should be "None of the above".
My thinking is that theoretically the thread referenced by myThread could remain in a Runnable state after starting with the main thread continuing to run. The main thread would call start() on the thread referenced by thread. At that point, myThread and thread would both be in the pool of Runnable threads and you cannot predict which one of them the thread scheduler would choose to run first. I thought that would mean the output is not guaranteed to be: "MyThread: start() followed by MyRunnable:run()" but could possibly be "MyRunnable: run() followed by MyThread: start()".
I don't know if I am wrong and if there something that I'm not understanding. I just want to make sure I know what the correct logic is should there be a similar question on the actual test. Could someone please help me with this? Thanks very much in advance!