java基础知识回顾之java Thread类学习(十一)--join方法的理解
以下面例子说明下面的源码:main 线程 和 A线程,A线程是main线程创建并且启动的,main线程优先级比较高,正在执行;
这个时候main线程调用A.join()之后,main线程一直等待,直到A线程运行完毕,main线程才运行。
join方法的源码:
* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever. * * <p> This implementation uses a loop of {@code this.wait} calls * conditioned on {@code this.isAlive}. As a thread terminates the * {@code this.notifyAll} method is invoked. It is recommended that * applications not use {@code wait}, {@code notify}, or * {@code notifyAll} on {@code Thread} instances. * * @param millis * the time to wait in milliseconds * * @throws IllegalArgumentException * if the value of {@code millis} is negative * * @throws 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.
*/
// 加锁当前线程
public final synchronized void join(long millis) throws InterruptedException { long base = System.currentTimeMillis(); long now = 0; if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (millis == 0) {
//A线程是start,在运行中 while (isAlive()) {
//main线程等待 wait(0); } } else {
//join(timeOut)的情况 while (isAlive()) {
//根据当前timeout的时间-now 是否<=0进行判断,主线程是否继续阻塞等待 long delay = millis - now;
//等待超时时间到了,则主线程不阻塞了,等待结束 if (delay <= 0) { break; } wait(delay);
//子线程从循环开始到现在运行的时间 now = System.currentTimeMillis() - base; } } }
给一个例子来理解:
package concurrentMy.joins;
/**
*
* @author Administrator
*
* main 线程 和 A线程,A线程是main线程创建并且启动的,main线程优先级比较高,正在执行;
* 这个时候main线程调用A.join()之后,main线程一直等待,直到A线程运行完毕,main线程才运行
*
*/
class ThreadA extends Thread {
public ThreadA(String name){
super(name);
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
// 复写父类的toString方法, 返回该线程的字符串表示形式,包括线程名称、优先级和线程组。
System.out.println(Thread.currentThread().getName() + "-" + i);
}
}
}
public class JoinDemo {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
ThreadA A = new ThreadA("线程A");
A.start();
A.join(); //A线程加入到“main线程”中,main线程一直等待,直到A线程执行完毕,main线程才运行
System.out.println(Thread.currentThread().getName() + "执行");
System.out.println(Thread.currentThread().getName() + "执行终止");
}
}
输出结果:
线程A-0
线程A-1
线程A-2
线程A-3
线程A-4
线程A-5
线程A-6
线程A-7
线程A-8
线程A-9
线程A-10
线程A-11
线程A-12
线程A-13
线程A-14
线程A-15
线程A-16
线程A-17
线程A-18
线程A-19
main执行
main执行终止
代码运行整个过程说明入下图:
Face your past without regret. Handle your present with confidence.Prepare for future without fear. keep the faith and drop the fear.
面对过去无怨无悔,把握现在充满信心,备战未来无所畏惧。保持信念,克服恐惧!一点一滴的积累,一点一滴的沉淀,学技术需要不断的积淀!