Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Thread sleep

Status
Not open for further replies.

WebGoat

MIS
Jul 16, 2005
85
US
Code:
public static void main(string args[])
{

 for(int k=0;k<2;k++)
  {
	
    WorkerThread wk=new WorkerThread();
    
    wk.start();
   
    Thread.sleep(500);  // who will sleep ? main thread or wk ?


who will sleep ? main thread or wk ?


Code:
sleep

public static void sleep(long millis)
                  throws InterruptedException

    Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors.


after calling wk.start() what is the current executing thread ? i have read that even if you call start() method there is no gurantee that wk thread will be started. so, who will sleep ?
 
If this is an academic hypothetical question, I'm afraid I don't have an answer, but can't you just tell the specific OBJECT to sleep? e.g., wk.sleep(500);

If you want a specific thread to sleep, you can store them in an array of size 2 (from your code example). To get the last thread started to sleep, for example, you'd have something like:

Code:
[b]Thread threadHolder = new Thread[2];[/b]
for(int k=0;k<2;k++)
  {
    
    WorkerThread wk=new WorkerThread();
    [b]threadHolder[k] = wk;[/b]
    
    wk.start();
   
    [b]if(k>0)
     threadHolder[k-1].sleep(500);[/b]

'hope this helps.

--Dave
 
javadoc for sleep said:
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.

So since the main thread executes it, the main thread will sleep.

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy
 
The calling thread and only the calling thread will sleep.

LookingForInfo: the sleep method is static, it doesn't matter which thread you invoke it over.

The code you posted will make the current thread to sleep again and again, not the other ones.

Cheers,

Dian
 
Well okay. I haven't used threads in a long time. I saw an example online that seemed to use the instantiated objects to call the sleep() method, so I assumed, incorrectly, you could apply the method directly to the individual objects.

Thanks!

--Dave
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top