Java线程之join()

来源:互联网 发布:淘宝图片制作软件 编辑:程序博客网 时间:2024/05/21 22:28

Java中的join()方法就是:停止当前的线程,加入调用该方法的线程

试用场景就是,当某个线程需要等待其他的线程结束以获取结果进行统计或者计算调用次方法是一个不错的选择:

public class ThreadJoin {    public String test(){        return "hello world";    }    class Thread1 extends Thread{        /**         * 调用父线程的构造函数         * @param threadName         */        public Thread1(String threadName){            super(threadName);        }        public void run(){            System.out.println("Thread1线程开始执行.....");            try {                sleep(1000);            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println("Thread1线程执行结束.....");        }    }    class Thread2 extends Thread{        private Thread1 thread1;        public Thread2(String threadName, Thread1 thread1){            super(threadName);            this.thread1 = thread1;        }        public void run(){            System.out.println("Thread2线程开始执行.....");            try {                thread1.start();                thread1.join();            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println("Thread2线程执行结束.....");        }    }    public void threadTest(){        Thread1 thread1 = new Thread1("Thread1");        Thread2 thread2 = new Thread2("Thread2", thread1);//        thread1.start();        thread2.start();    }}

在上面的代码中我们创建了两个线程Thread1和线程Thread2,首先我们启动线程2,然后在线程2中调用新城1的start()方法,线程1启动,然后在调用线程1的join()方法就是说让线程1 来执行,线程2被中断,知道线程1执行结束他才执行。


代码在我的github上地址是:https://github.com/lly576403061/thread_traning/tree/2016_06_15_thread_base

0 0