| Author |
Doubt in Threads
|
Nik Arora
Ranch Hand
Joined: Apr 26, 2007
Posts: 652
|
|
public class TwoThreads{ static Thread laurel,hardy; public static void main(String[] args){ laurel=new Thread(){ public void run() { System.out.println("A"); try{ hardy.sleep(1000); } catch(Exception e){ System.out.println("B"); } System.out.println("C"); } }; hardy=new Thread() { public void run(){ System.out.println("D"); try{ laurel.wait(); }catch(Exception e){ System.out.println("E"); } System.out.println("F"); } }; laurel.start(); hardy.start(); } } Hey how does this work. Can anyone explain please Thanks Nik
|
 |
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
|
|
|
What does it do when you compile and run it? What don't you understand about the output? What did you expect?
|
Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
|
 |
Nik Arora
Ranch Hand
Joined: Apr 26, 2007
Posts: 652
|
|
Hi Barry, The output is : A C D E F I am not understanding the output.
|
 |
Greg Noe
Greenhorn
Joined: Apr 20, 2007
Posts: 6
|
|
|
Well, this question is from the K&B book and there's an answer in there too. B is not printed because even though laurel doesn't own the lock on hardy, calling hardy.sleep() doesn't throw an exception because sleep() just sleeps whatever method is currently running, it ignores where it is originating from. wait() on the other hand, requires a lock on the object that's calling it, so it will thrown an exception, and thus E is printed.
|
 |
 |
|
|
subject: Doubt in Threads
|
|
|