线程join()坑爹

join死主线程跟着死

join()方法的作用,是等待这个线程结束;

也就是说,t.join()方法阻塞调用此方法的线程(calling thread)进入 TIMED_WAITING 状态,直到线程t完成,此线程再继续;

通常用于在main()主线程内,等待其它线程完成再结束main()主线程。

例子之没有join

public class TestJoin
{
    public static void main(String[] args)throws 
    InterruptedException 
    {
        Thread t1 = new Thread()
        {
            @Override
            public void run()
            {
                try{
                    sleep(5000);
                    System.out.println("thread1,");
                } catch (Exception e)
                {e.printStackTrace();}
            }
        };
        Thread t2 = new Thread()
        {
            @Override
            public void run()
            {
                System.out.println("thread2,");
            }
        };
        t1.start();
        t2.start();
        System.out.println("game over");
    }
}

执行顺序是主线程开始-->主线程结束-->线程二开始-->线程二结束-->线程一开始-->线程一结束

//输出结果,线程一延迟了5秒,基本上就是后执行
game over thread2, thread1,

例子之有join

t1.start();
t1.join();//join加入
t2.start();
System.out.println("game over");

执行顺序
主线程开始-->线程一开始(sleep五秒)-->线程一结束-->输出game over-->主线程结束-->线程二开始-->线程二结束

//输出结果
thread1, game over thread2,
原文地址:https://www.cnblogs.com/lhh666/p/11707669.html