I'm playing around with threads and I'm wondering if it's possible to force a thread to execute something.
So the thing is I have some method like this:
public void asyncSleep() {
Supplier<Boolean> sleeper = () -> {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
}
return true;
};
CompletableFuture<Boolean> promise = CompletableFuture.supplyAsync(sleeper, ex);
promise.thenAccept(u -> {
System.out.println("thread=" Thread.currentThread());
});
}
And I'd need the original thread (the one executing the asyncSleep()
method) to be the one executing the thenAccept. Is that even possible? And if so, how can I do it?
CodePudding user response:
If you want it to be working in the non blocking way and you still want that original thread (the one that executes asyncSleep
) to also execut method that you pass into thenAccept
then the only way is as follows:
You'd need to use an ExecutorService
with just single thread. Execute asyncSleep
with this executor, but then, you'll have to pass the same executor into thenAcceptAsync
(instead of thenAccept
) as a second argument.
Then if your thread didn't crash and wasn't replaced by the executor with new thread, it should be exactly the same thread executing both methods.
But that's an artificial use case.