Win a copy of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Doubt in Threads

 
Ranch Hand
Posts: 652
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Barry,
The output is :

A
C
D
E
F

I am not understanding the output.
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic