join()方法如何在多线程中工作

时间:2019-01-12 14:14:06

标签: java multithreading

根据我对join()方法的理解,它允许一个线程等待另一个线程完成。

然后,根据我的代码:一旦线程(t0)结束,线程(t3)就应该启动,这不会发生

public class Threaded extends Thread {

     @Override
     public void run() {

      for (int i=0; i<5; i++) {

           System.out.println(Thread.currentThread().getName() + ": " + i);

       }

       }

}

public class Demo {

    public static void main(String[] args) throws InterruptedException {

        Thread main = Thread.currentThread();

        Threaded t0 = new Threaded();
        Threaded t1 = new Threaded();
        Threaded t2 = new Threaded();
        Threaded t3= new Threaded();

        t0.start();
        t1.start();
        t2.start();

        t0.join();

        t3.start();

    }

}

输出为

main 5  
Thread-1: 0  
Thread-2: 0  
Thread-0: 0  
Thread-2: 1  
Thread-2: 2  
Thread-1: 1  
Thread-2: 3  
Thread-2: 4  
Thread-0: 1  
Thread-0: 2  
Thread-0: 3  
Thread-0: 4  
Thread-1: 2  
Thread-1: 3  
Thread-1: 4  
Thread-3: 0  
Thread-3: 1  
Thread-3: 2  
Thread-3: 3  
Thread-3: 4

在此输出中,线程3在线程0,线程1和线程2结束之后开始。 但是,据我所知,线程0结束后,线程3即开始启动。

2 个答案:

答案 0 :(得分:3)

  

线程3结束时,线程3就会启动。

线程3完成后,线程3即可运行。但这并不意味着立即安排。可能同时有3个可运行线程,并且不确定哪个线程先打印。

答案 1 :(得分:1)

Thread.join()等待该线程死亡。基本上所有线程都在主线程上运行。因此,让我尝试解释您的代码流程。

public static void main(String[] args) throws InterruptedException {

    Thread main = Thread.currentThread();

    // you have created 4 Thread instances here...
    Threaded t0 = new Threaded();
    Threaded t1 = new Threaded();
    Threaded t2 = new Threaded();
    Threaded t3= new Threaded();

    // you have started t0, t1 and t2 to run on top of main thread
    t0.start();
    t1.start();
    t2.start();

    // here you have used Thread.join()
    // so your main thread will wait here, 
    // it will wait for the completion of t0 
    t0.join();

    // so after the completion of t0, t3 will start
    t3.start();

}

因此,对于您的问题,您的线程t1,t2和t3都在可运行的线程池中。因此,现在选择哪个线程并执行完全由Thread Scheduler负责。