★ 2.5 等待一个线程-join()
★★★A中调用B.join表示 B先完成后A再继续
有时,我们需要等待一个线程完成它的工作后,才能进行自己的下一步工作。例如,张三只有等李四转账成功,才决定是否存钱,这时我们需要一个方法明确等待线程的结束
public class ThreadJoin {
    //样例一
//    public static void main(String[] args) throws InterruptedException {
//        Runnable target = () -> {
//            for (int i = 0; i < 10; i++) {
//                try {
//                    System.out.println(Thread.currentThread().getName()
//                                       + ": 我还在工作!");
//                    Thread.sleep(1000);
//               } catch (InterruptedException e) {
//                    e.printStackTrace();
//               }
//           }
//            System.out.println(Thread.currentThread().getName() + ": 我结束了!");
//       };
//        Thread thread1 = new Thread(target, "李四");
//        Thread thread2 = new Thread(target, "王五");
//        System.out.println("先让李四开始工作");
//        thread1.start();
        thread1.join();
//        System.out.println("李四工作结束了,让王五开始工作");
//        thread2.start();
        thread2.join();
//        System.out.println("王五工作结束了");
//   }
    //样例二
    public static void main(String[] args) {
        Thread t2 = new Thread(()->{
            for(int i = 1; i <= 10000;i++){
                System.out.printf("t2工作%d %n",i);
            }
        });
        Thread t1 = new Thread(()->{
            //t2先工作
            try {
                t2.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for(int i = 1; i <= 10000; i++){
                System.out.printf("t1工作%d %n",i);
            }
        });
        t2.start();
        t1.start();
    }
}
join用于让主线程休眠
大家可以试试如果把两个 join 注释掉,现象会是怎么样的呢?
附录
| 方法 | 说明 | 
|---|---|
| public void join() | 等待线程结束 | 
| public void join(long millis) | 等待线程结束,最多等 millis 毫秒 | 
| public void join(long millis, int nanos) | 同理,但可以更高精度 | 
关于 join 还有一些细节内容,我们留到下面再讲解。
应用:
 
★★★另一种方法 setDaemon(主线程结束,后台线程也结束)
public class Thread_setDaemon {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            while (true) {
                System.out.println("hello");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "这是俺的线程");
        // 使用 setDaemon 设置成后台线程.
        // 设置操作得在 start 之前. 如果线程启动了, 就改不了了!!
        t.setDaemon(true);
        t.start();
        System.out.println("main 线程执行结束. ");
    }
}









![[神经网络]Anchor_Free网络(YoloX,CenterNet)](https://img-blog.csdnimg.cn/7708646d041542eb8daa741d387267f7.png)








