Phate
Phate

Reputation: 6602

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?

Upvotes: 2

Views: 2159

Answers (1)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62854

You can use ScheduledThreadPoolExecutor. For example:

var scheduler = Executors.newScheduledThreadPool(1);


var scheduledFuture = scheduler.schedule(this::method,  5, TimeUnit.SECONDS);


public String method() {
    System.out.println("Executed!");
    return "Called!";
}

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.

Upvotes: 4

Related Questions