Search code examples
javajava-threads

Java - fire action after specific Thread has ended


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!


Solution

  • 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");
        });