Alex Rivera | Logout

Thread join on itself

Asked 2011-05-14T03:18:16.233
37

I am in doubt, what happens when a thread joins itself. i.e thread calls the join method on its own. I am not getting any error.

Sample :

public class JoinItself extends Thread {

    public void run() {
        System.out.println("Inside the run method ");
        System.out.println(Thread.currentThread().isAlive());
        for(int i=0;i<5;i++) {
            try {
                System.out.println("Joining itself ...");
                Thread.currentThread().join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {

        JoinItself j = new JoinItself();

        System.out.println(j.isAlive());
        j.start();
        System.out.println(j.isAlive());
        System.out.println("Thread started ...");

    }

}

But Why? Should I get any error?

Edit
Report

1 Answer

3

Should I get any error ?

I wouldn't expect an error. The javadocs for Thread.join() do not say that this is an error, and it is just conceivable that some crazy person may use this as another way of doing a sleep, so an undocumented error would be a bad idea.

I guess that Sun didn't think this was a case that was worth giving special attention to.

answered 2011-05-14T07:32:24.670

Your Answer