user5047085
user5047085

Reputation:

setTimeout using Java Thread

Say I have this:

  private static ExecutorService executor = Executors.newFixedThreadPool(1);

  executor.execute(() -> {
     Thread.sleep(100);
      doSomething();
  });

since I am reusing a thread, I am blocking it if others want to use the thread. My question is - is there a way to simply register a callback, something like this:

   executor.execute(() -> {
        timers.setTimeout(() -> {  // imaginary utility
             doSomething();
        },100);
   });

is this possible with core Java?

Upvotes: 4

Views: 172

Answers (1)

user5047085
user5047085

Reputation:

Yeah it looks like this works fine, I tested it on Java 10:

CompletableFuture.delayedExecutor(1, TimeUnit.MILLISECONDS).execute(() -> {
    doSomething();
});

Upvotes: 3

Related Questions