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 Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

loop until thread is non-sleeping 1

Status
Not open for further replies.

almoes

Programmer
Jan 8, 2003
291
US
Hi all!

At a point in my code I want to stop the process and introduce a delay. This delay I make it setting a thread to sleep, and making a while loop doing nothing until the thread wakes up and sets a variable. Is this stable enough? Any other suggestions? thanxs.

cheers,
alej
 
I've never had any problems with Thread.sleep() ...
 
But it will be ok to have a while loop doing nothing until the thread wakes up? this is my worry.

cheers,
alej
 
If you want to wait until something happens, you can also use the wait() and notify() methods ot the Object class.

Cheers.

Dian
 
but this will block the other code? how?

cheers,
alej
 

You mean like this ?
Code:
...

boolean b = false;

...

while (b) {
  try { Thread.sleep(1000); } catch (Exception e) {}
}

// carry on
 
In fact I think I complicated it more...I just want a delay before continuing with the code, but to be able to interrupt this delay. So what I did was create a timer class, which I control by a variable status. So while the status is not 2, do nothing:

myTimer.init(delay);
while (myTimer.status!=2){}
... then continue

init(delay) starts the thread and puts it to sleep for delay milliseconds

Am I complicating the whole thing?

cheers,
Alej
 
>>> Am I complicating the whole thing?

I guess that depends on your viewpoint ! If you just want to have a delay in the code, depending on a value (ie boolean) then the method I posted earlier will work fine ...
 
thanxs for the feedback but i discovered that I cant really stop the code and need to execute it in parallel threads (which I was trying to avoid) but have no other way around.

cheers,
Alej
 
To be sincere, I still don't understand what are you trying to do. Just stop the program waiting for some event with a max time without multithreading?

Then you can use

initialTime = System.currentTimeMilis();
while (!someFlag && (System.currentTimeMilis()-initialTime)<someTime);

Anyway, I'd suggest the multithreading option.

Cheers.

Dian
 
Thanxs but I think I cant avoid multi-threading.

cheers,
Alej
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top