Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in Threads

 
Nik Arora
Ranch Hand
Posts: 652
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What does it do when you compile and run it? What don't you understand about the output? What did you expect?
 
Nik Arora
Ranch Hand
Posts: 652
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Barry,
The output is :

A
C
D
E
F

I am not understanding the output.
 
Greg Noe
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic