Understanding join() method example

前端 未结 4 464
野趣味
野趣味 2020-12-15 08:22

The Java thread join() method confuses me a bit. I have following example

class MyThread extends Thread {
    private String name;
    private int sleepTime;         


        
4条回答
  •  攒了一身酷
    2020-12-15 08:42

    There is a main thread which starts the four customs threads you created t1,t2,t3 and t4. Now when join() method is invoked on a thread and no argument(time) is supplied(which makes it 0 by default meaning maximum wait time is forever) then the calling thread will wait for the thread on which join was invoked to terminate.

    When t1.start() is called it's corresponding run() method is invoked by the JVM. Since waitsFor argument is null for t1 it will simply terminate by printing it's name. Since you are adding sleep t2,t3,t4 would be started by the time t1 completes it's sleep. Now t2 will wait for t1 to terminate as we are calling join on t1 from t2. Similarly t3 will wait for t2 and t4 will wait for t3. So youe execution will go t1->t2->t3->t4.

    However if t1 terminates before t2 calls join on it, join will simply return because at that point(when t2 calls join on t1) isAlive() will be false.

提交回复
热议问题