This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread Question-JQ++" Watch "Thread Question-JQ++" New topic

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()
public static void main(String args[])
new Test("String1").start();
new Test("String2").start();
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: 2591

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.
- Manish
I agree. Here's the link:
subject: Thread Question-JQ++
It's not a secret anymore!