Reputation: 89
I am working on a JavaFx project in which there is a sleep in look method like this :
public void run() {
while (true) {
try {
method1()
Thread.sleep(2000);
Runnable1
Thread.sleep(10000);
if (condition 1){
method2
Thread.sleep(10000);
}else{
Runnable3
Thread.sleep(20000);
}
switch ()
case 1
Runnable 1
Thread.sleep(12000);
case 2
Runnable 4
Thread.sleep(12000);
case 3
Thread.sleep(5000);
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
break;
}
}
The problem is that the "case when, and if else" succession is very complex (around 20 branches).
Is there a better way to do that than to use always "Thread.sleep".
Upvotes: 0
Views: 323
Reputation: 140494
There is almost always a better way than Thread.sleep
.
It's very brittle, because there is no guarantee the "thing" happens within that sleep time, unless you crank up the sleep time so much that you are waiting unnecessarily long (and even then, there is no guarantee).
You are presumably waiting for some condition to change; so perhaps look at Condition
; or look at something like Future
(incl CompletableFuture
) to do something when a previous task completes.
Upvotes: 1