File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread Question-JQ++

 
Arun Pai
Ranch Hand
Posts: 143
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2591
Android Firefox Browser Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic