首页 > 编程语言 > 详细

线程join()坑爹

时间:2019-10-20 16:23:34      阅读:46      评论:0      收藏:0      [点我收藏+]

join死主线程跟着死

例子之没有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,

 

线程join()坑爹

原文:https://www.cnblogs.com/lhh666/p/11707669.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!