简体   繁体   中英

Is there any alternative to Thread.sleep()?

I need to perform some waiting between one call and another. Problem is that this waiting will be made in a library so it is not a good practice to put a Thread.sleep() there. No swing involved, this library is a jna interface.

So..is there any alternative suited for my case?

You can use ScheduledThreadPoolExecutor . For example:

ScheduledExecutorService scheduledExecutorService =
        Executors.newScheduledThreadPool(1);

    ScheduledFuture scheduledFuture =
        scheduledExecutorService.schedule(new Callable() {
            public Object call() throws Exception {
                System.out.println("Executed!");
                return "Called!";
            }
        },
        5,
        TimeUnit.SECONDS);

First a ScheduledExecutorService is created with one thread in.

Then an anonymous implementation of the Callable interface is created and passed to the schedule() method. The two last parameters specify that the Callable should be executed after 5 seconds.

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