aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt  in Threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt  in Threads" Watch "Doubt  in Threads" New topic
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