多线程join(),可以有无参的和有参的,join(long mills).join方法是Thread 提供的方法,join方法主要用于实现当此线程死亡后开始执行后面的代码是阻塞型的。对于join(long mills)方法,可实现当等待线程死亡时间为mills,也就意味着最多等待mills时间,可执行后续代码

join源码分析如下:

线程join()方法

特点:能够阻塞其他线程的执行

场景:ABC3个线程实现顺序执行,即执行A->B->C,则B中run方法中 a.join(),C中 b.join(),跟ABC三个线程的启动顺序无关

示例代码如下:

public class ThreadCommunication2 {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("I'm comming first!");
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    thread1.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("jack commmig second");
            }
        });
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    thread2.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("rose commmig thrid");
            }
        });

        thread2.start();
        thread3.start();
        thread1.start();
    }
}

运行结果:

I'm comming first!
jack commmig second
rose commmig thrid



相关文章: