• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threading question from Dan's site

 
s khosa
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
This is the question on Threads from Dan's site:
class A extends Thread {
public void run() {
synchronized (this) {
try{wait();} catch (InterruptedException ie){}
}
}
public static void main(String[] args) {
A a1 = new A();
long startTime = System.currentTimeMillis();
a1.start();
System.out.print(System.currentTimeMillis() - startTime + ",");
}
}

What are the possible results of attempting to compile and run the program?
a. The number printed is greater than or equal to 0.
b. The synchronized block inside the run method is not necessary.
c. This program runs to completion after the elapsed time is printed.
d. Compiler error.
e. Run time error.
f. None of the above.
Answer is : a
But could one of the outcomes not be (f)- None of the above becuase what is the a1.start() call starts the thread a1 first and does not reach print statement. Is it not possible?
Thanks,
Sumeer.
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sumeer
I would say that it's not posible. This is because when a1.wait() is called thread a1 is not in the runnable state. So as for this question the only other thread(main thread) should complete. Only other thread refers to the thread that is being made in this prorgram. There might also be some other threads like garbage collection thread/s that might also run.
 
G Nadeem
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
talking from exam point of view, i think before going for 'f' we must make sure that none of the given options is valid. if a valid option is given, 'none-of-above' is inapplicable. am i right??. if not can we, select a set of options with one being 'none-of-above' too. plz give ur opinon.
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a1 thread is started before main thread reaches print, it would be a1 the one waiting. main thread can proceed to execute the pritn statement.
Because a1 is not notified it keeps waiting forever and the program should not end to completion.
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by G Nadeem:
hi,
talking from exam point of view, i think before going for 'f' we must make sure that none of the given options is valid. if a valid option is given, 'none-of-above' is inapplicable. am i right??. if not can we, select a set of options with one being 'none-of-above' too. plz give ur opinon.

If the "none of the above" option is correct, then no other option is correct.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic