1、线程挂起join简介
将另外一个线程join到当前线程,则需要等到join进来的线程执行完才会继续执行当前线程。
thread.join(); //当前线程挂起,调用线程 thread,在thread线程执行完毕之前,当前线程一直挂起不执行。
thread.join(1000); //当前线程挂起,调用线程 thread,等待 thread 线程,等待时间是1000毫秒,超过这个时间,当前线程进入可运行状态。
2、代码事例
package com.xxx.util;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* Created with IntelliJ IDEA.
* Date: 15-3-27
* Time: 上午9:38
* To change this template use File | Settings | File Templates.
*/
public class ThreadJoin1 implements Runnable{
@Override
public void run() {
System.out.printf("Beginning threadJoin1 loading:%s\n",new Date());
try {
TimeUnit.SECONDS.sleep(6);
} catch (InterruptedException e) {
System.out.println("ThreadJoin1 has bean interrupted");
}
System.out.println("ThreadJoin1 loading has finished.");
}
}
package com.xxx.util;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* Created with IntelliJ IDEA.
* Date: 15-3-27
* Time: 上午9:38
* To change this template use File | Settings | File Templates.
*/
public class ThreadJoin2 implements Runnable{
@Override
public void run() {
System.out.printf("Beginning threadJoin2 loading:%s\n",new Date());
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
System.out.println("ThreadJoin2 has bean interrupted");
}
System.out.println("ThreadJoin2 loading has finished.");
}
}
main类
package com.xxx.util;
import java.util.Date;
/**
* Created with IntelliJ IDEA.
* Date: 15-3-27
* Time: 上午9:44
* To change this template use File | Settings | File Templates.
*/
public class ThreadJoinMain {
public static void main(String[] args){
Thread threadJoin1 = new Thread(new ThreadJoin1());
Thread threadJoin2 = new Thread(new ThreadJoin2());
threadJoin1.start();
threadJoin2.start();
try {
//main线程等待threadJoin1线程1秒,超过一秒,main线程进入可运行状态
threadJoin1.join(1000);
threadJoin2.join();
} catch (InterruptedException e) {
System.out.println("Handle InterruptedException.");
}
System.out.printf("%s:Configuration has bean loaded:%s\n",Thread.currentThread().getName(),new Date());
}
}
3、运行结果
当前线程挂起等待。