Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - fire action after specific Thread has ended [duplicate]

This is my code:

Thread T = new Thread() {
    public void run() {
        //some code here...
    }
};
T.start();

I need to know when this specific thread has finished so I can start another code right afterwards, something like this hypothetical option:

T.finished(){
    //some code here
}

EDIT: the solution provided by @swpalmer is the most straightforward and the easiest compared to all the other ones, I would not consider this being a duplicate as the accepted solution is different to the others and is really extremely easy to implement, yet doing what it should and what I was asking for!

like image 474
qraqatit Avatar asked Apr 06 '26 23:04

qraqatit


2 Answers

Here:

 public void run() {
    //some code here...
    whatever.finished();
 }

That is the straight forward way of solving this: your last action in your thread is to send that "event".

Sure, you can also use Thread.join() to do that from the outside.

like image 75
GhostCat Avatar answered Apr 08 '26 14:04

GhostCat


Instead of Thread, consider using java.util.concurrent.CompletionStage

You can chain together actions using whenComplete() or one of the other methods.

See examples here

    CompletableFuture.runAsync(() -> {
        //some code here...
        System.out.println("Hi!");
    }).thenRun(() -> {
        //some code here
        System.out.println("Greeting completed");
    });
like image 44
swpalmer Avatar answered Apr 08 '26 14:04

swpalmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!