线程中join的用法

 join是Thread类的方法

/**
* Waits for this thread to die.
*
* @exception InterruptedException if any thread has interrupted
* the current thread. The <i>interrupted status</i> of the
* current thread is cleared when this exception is thrown.
*/

从注解上看  是等待线程死去,即锁住当前线程知道线程死去

join方法 让线程顺序执行,他内部也是锁的实现机制
 所以join的作用就相当于阻塞掉除了当前线程以外的所有的线程(包括主线程),等待自己执行结束,
 并且遵守先来后到的排队原则,先join的先执行,后join后执行,
 必须注意的是,最后的线程不能使用join,否则线程就全部在等待中,
 所以根据Thread的join()方法的特性,可以实现线程的同步。

来看一个demo

public class JoinTest {
//测试 join()方法是不是线程安全的
public static void main(String[] args) throws InterruptedException {
System.out.println("主方法运行:"+Thread.currentThread().getName());
startFirstThread();
startSecondThread();
System.out.println("主方法运行结束"+Thread.currentThread().getName());

}
private static void startFirstThread(){
Thread thread1 = new Thread(){
@Override
public void run() {
for (int i = 0; i < 5; i++){
System.out.println("线程方法0:"+Thread.currentThread().getName()+ "运行次数"+ i);
}
}
};
thread1.start();
try {
thread1.join();
} catch (Exception e) {
e.printStackTrace();
}
}

private static void startSecondThread(){
Thread thread2 = new Thread(){
@Override
public void run() {
for (int i = 0; i < 5; i++){
System.out.println("线程方法1:"+Thread.currentThread().getName()+ "运行次数"+i);
}
}
};
thread2.start();
try {
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

运行结果如下:

主方法运行:main
线程方法0:Thread-0运行次数0
线程方法0:Thread-0运行次数1
线程方法0:Thread-0运行次数2
线程方法0:Thread-0运行次数3
线程方法0:Thread-0运行次数4
线程方法1:Thread-1运行次数0
线程方法1:Thread-1运行次数1
线程方法1:Thread-1运行次数2
线程方法1:Thread-1运行次数3
线程方法1:Thread-1运行次数4
主方法运行结束main

注释掉   thread1.join(); 和 thread2.join();

运行结果如下

主方法运行:main
主方法运行结束main
线程方法0:Thread-0运行次数0
线程方法0:Thread-0运行次数1
线程方法0:Thread-0运行次数2
线程方法0:Thread-0运行次数3
线程方法1:Thread-1运行次数0
线程方法0:Thread-0运行次数4
线程方法1:Thread-1运行次数1
线程方法1:Thread-1运行次数2
线程方法1:Thread-1运行次数3
线程方法1:Thread-1运行次数4

注释掉   thread2.join()  

运行结果如下

主方法运行:main
线程方法0:Thread-0运行次数0
线程方法0:Thread-0运行次数1
线程方法0:Thread-0运行次数2
线程方法0:Thread-0运行次数3
线程方法0:Thread-0运行次数4
主方法运行结束main
线程方法1:Thread-1运行次数0
线程方法1:Thread-1运行次数1
线程方法1:Thread-1运行次数2
线程方法1:Thread-1运行次数3
线程方法1:Thread-1运行次数4

可以看到不就join方法  线程执行的顺序是随机的

加上join方法  main线程在最后执行。

如果不足,欢迎留言。一起讨论

 

posted @ 2018-07-26 17:51  奋斗的渣渣  阅读(713)  评论(0编辑  收藏  举报