my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread Question-JQ++ Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread Question-JQ++" Watch "Thread Question-JQ++" New topic
Author

Thread Question-JQ++

Arun Pai
Ranch Hand

Joined: Mar 11, 2002
Posts: 143
Question ID :954811098580
What will be the result of attempting to compile and run the following program?
public class Test extends Thread
{
String msg = "default" ;
public Test(String s)
{
msg = s;
}
public void run()
{
System.out.println(msg);
}
public static void main(String args[])
{
new Test("String1").start();
new Test("String2").start();
System.out.println("end");
}
}
choices;
1. Program fails to compile
2. prints string1, string2 and end in that order.
3. Prints string1, string2 in random followed by end.
4. it will always print end first.
5. No guarantee of order of execution.
Answer given is 5 with explanation
After doing new Test("String2").start(), there are 3 threads ready to run ( in fact, one running and 2 ready to run. The main() thread and the 2 newly created ones). JVM can choose any thread to run and any thread to suspend any time. So no order is guaranteed.
What is wrong in selecting 4? Infact when I compile and run I always get end, string1, string2 in that order. Gods Must be crazy I am going nuts
Manish Hatwalne
Ranch Hand

Joined: Sep 22, 2001
Posts: 2578

5. No guarantee of order of execution
is the right answer. Remember in threads you can't always conclude from the o/p on ur screen. Thread scheduling is platform dependent, so it is quite possible that on certain platforms the "end" will not be printed first.
HTH,
- Manish
 
 
subject: Thread Question-JQ++
 
Similar Threads
Threads
Testing Strings
JQPlus Q answer is wrong??
Thread
Why this does not fail?