简体   繁体   中英

Thread.sleep performance vs other solutions

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".

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM