Understanding join() method example

前端 未结 4 462
野趣味
野趣味 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.

    0 讨论(0)
  • 2020-12-15 08:54

    It would terminate in order t1, t2, t3, t4... join causes the currently executing thread to wait until the thread it is called on terminates.

    0 讨论(0)
  • 2020-12-15 09:02

    Surely the order of thread termination would be from t1, t2, and so on here. May be you will get a clear understanding of join() method in java thread from here also http://findnerd.com/list/view/Java-Thread-Join-Example/4465/

    0 讨论(0)
  • 2020-12-15 09:04

    What actually confuses you about Thread.join()? You haven't mentioned anything specific.

    Given that Thread.join() (as the documentation states), Waits for this thread to die, then t4 will wait for t3 to complete, which will wait for t2 to complete, which will wait for t1 to complete.

    Therefore t1 will complete first, followed by t2, t3, and t4.

    0 讨论(0)
提交回复
热议问题