Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

java - Understanding join() method example

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

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

    MyThread(String name, int stime, Thread wa) { … }

    public void run() {
        System.out.print("["+name+" ");

        try { Thread.sleep(sleepTime); }
        catch(InterruptedException ie) { }

        System.out.print(name+"? ");

        if (!(waitsFor == null))
        try { waitsFor.join(); }
        catch(InterruptedException ie) { }

        System.out.print(name+"] ");

And

public class JoinTest2 {
    public static void main (String [] args) {
        Thread t1 = new MyThread("1",1000,null);
        Thread t2 = new MyThread("2",4000,t1);
        Thread t3 = new MyThread("3",600,t2);
        Thread t4 = new MyThread("4",500,t3);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

In which order are the threads terminated?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...