stanwar
stanwar

Reputation: 191

java Thread.join doesn't work as expected

I have the following class

class ThreadDemo extends Thread {
    private Thread t;
    private String threadName;

    ThreadDemo( String name) {
        threadName = name;
    }

    public void run() {
        for(int i = 5; i > 0; i--) {
            System.out.println("Thread " +  threadName + " Counter   ---   "  + i );
        }

        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            System.out.println("Sleep issue");
        }

        System.out.println("Finishing run");

        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            System.out.println("Sleep issue");
        }
    }

    public void start () {
        t = new Thread (this, threadName);
        t.start ();
    }
}

which is tested like below

public class Main {
    public static void main(String[] args) {
        ThreadDemo T1 = new ThreadDemo( "Thread - 1 ");
        ThreadDemo T2 = new ThreadDemo( "Thread - 2 ");
        T1.start();
        T2.start();

        //Let's give some time for threads to run
        try {
            Thread.sleep(10);
        } catch (Exception e) {
            System.out.println("Main sleep issue");
        }

        try {
            T1.join();
            T2.join();
        } catch ( Exception e) {
            System.out.println("Interrupted");
        }

        System.out.println("Finishing main.");
    }
}

Why does I always get "Finishing main" before "Finishing run" in output despite the fact I used T1.join() and T2.join() to wait for them to finish? Initially I thought it could be due to buffer delay so I added Thread.sleep(1000) at the end of run() to give some time to print "Finishing run" but it didnt't help. I guess it's due to first occurrence of Thread.sleep(1000) (when I remove it, it work's fine) but have no idea why.

Upvotes: 0

Views: 285

Answers (1)

Andy Turner
Andy Turner

Reputation: 140318

It's because of this:

public void start () {
    t = new Thread (this, threadName);
    t.start ();
}

So your ThreadDemo instance is never actually started as a thread: the thread that is printing the Finishing run message is the one created in that method. There is no link between that thread and the ThreadDemo.

Remove the start() method.

Upvotes: 5

Related Questions