Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is Thread a static class?

 
Chiran Mathur
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If it is then why do we instantiate Thread in this manner
Thread t=new Thread().
If it is not, then how can we use Thread in the following manner:
class A implements Runnable{
public void run(){
System.out.println("Hello I am there");

try{
Thread.sleep(500);
}
catch(InterruptedException e){
System.out.println("Hey I caught it!!");
}
}
}
I am confused here...
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Briefly,
sleep() is a static method declared in the Thread class.
The statement
Thread.sleep() is perfectly legal and does not mean that Thread is a static class. Thread is a top-level class and top-level classes cannot be static.
 
Mandar Puranik
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Chiran,
I will try to explain it.
When you do a Thread t = new Thread();
it instantiates a new object t, of type Thread.
But when you are doing a Thread.sleep();
you are telling the program, which itself is a thread, to do a sleep.
i.e you can do a t.sleep(), in your example.
Ranchers, let me know if I am correct.
Thanks
Mandar
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sleep(x) causes the currently executing thread to sleep during x milliseconds. Note that the currently executing thread is not necessarly the "program" as you mentioned.
Invoking a static method on a reference (t.sleep()) is considered a bad practice and should not be done in "good" code (see Java coding conventions: 10.2 Referring to Class Variables and Methods )
[ January 29, 2003: Message edited by: Valentin Crettaz ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic