Reputation: 4103
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
Reputation: 240900
while(true){
if (checkcondition1) {
//some code
} else {
try {
Thread.sleep(20*1000);
} catch (Exception ex) {
//some action
}
}
Upvotes: 3
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