Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining threads in java

(Thread) A.join() - causes current thread to wait for the thread A to complete. I supposed then that calling this.join() from the run method will cause thread to deadlock - that it will wait for itself to complete. However it doesn't happen - code compiles and runs just fine - without deadlock. What happens when I call this.join() then?

like image 768
mary jane Avatar asked Aug 30 '26 12:08

mary jane


1 Answers

The OP uses this.join() in the provided example

Nathan in his example uses Thread.currentThread().join() instead.

By using this.join() a new thread is created which is getting joined, but the main thread is intact.

@Nathan The following works as intended:

public class Main extends Thread {

    @Override
    public synchronized void run() {
       super.run();
       try {
           this.join();
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
    } 

    public static void main(String[] args) {
        new Main().start();
        System.out.println("hello");
    }
}
like image 84
C.L.S Avatar answered Sep 01 '26 00:09

C.L.S



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!