vaibhav
vaibhav

Reputation: 4103

Java thread wait/sleep

I have the below condition, Can someone please help:

if(checkcondition){ --------(A)
...
some code
...
}
else{
sleep for 20 sec
go back to checkconfdition loop @ (A)
}

Any help is appriciated in advance.

Thanks Vaibhav

Upvotes: 1

Views: 1863

Answers (2)

Jigar Joshi
Jigar Joshi

Reputation: 240900

while(true){
    if (checkcondition1) {
        //some code
    } else {
        try {
           Thread.sleep(20*1000);
        } catch (Exception ex) {
        //some action
    }
}

Upvotes: 3

Nick H
Nick H

Reputation: 11535

Sleeping is not the best way to get a thread to wake up and do stuff. You should use call wait to make the thread wait, and then your other thread that sets the checkcondition would also call notify to wake the first thread up.

The advantage of doing this is that the thread will wake up straight away, instead of having to wait up to 20 seconds for it to realise there's work to do.

Search for Java wait notify and you'll find plenty of examples. Related Stack Overflow question: A simple scenario using wait() and notify() in java.

Upvotes: 3

Related Questions