Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt related to sleep() in Thread

 
Jolly Tiwari
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi! All,

I have a doubt related to static sleep() method in Thread class.
if we have a code snippet like
...
.
public static void main(String...s)
{
MyRunnable mr=new MyRunnable();
Thread t1=new Thread(mr);
t1.start();
t1.sleep(40000);
}
...
...
...
As sleep is a static method ,so reference of user created thread (t1) will be used to retrieve the class name i.e Thread class and in that case the currently running thread ,which is the main thread will go to sleep if main thread is currently executing even we had called sleep() in thread t1.

Please tell me what actually goes on in this scenario.

Regards

Jolly
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think, You are right..I think it will be decided at the compile time that which method is to be called. This code is equivalent to following:

public static void main(String...s)
{
MyRunnable mr=new MyRunnable();
Thread t1= null;
//t1.start(); --> To avoid null pointer exception
t1.sleep(40000);
}


I think this code will work and in this case it will cause main thread to sleep, Same applies to your code also. I will curious to know the exact answer and will keep eye on this post.
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use CODE tags when you post code.

public static void main(String...s)
{
MyRunnable mr=new MyRunnable();
Thread t1=new Thread(mr);
t1.start();
t1.sleep(40000);
}


This code will not compile since you did not handle the InterrptedException.

The sleep method is invoked natively. Which means that java uses native code to figure out how to sleep, which makes sense in a lot of ways. You will have to grab the native implementation to figure out whats going on
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jolly tiw:
...the currently running thread ,which is the main thread will go to sleep if main thread is currently executing even we had called sleep() in thread t1...

That's exactly right!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic