Thread join的原理
先写段都知道的代码,一个主类,两个线程类,保证线程的执行先后顺序,使用join方法。
package com.dl.study.m4;
public class TestThread {
public static void main(String[] args) throws InterruptedException {
ThreadOne one = new ThreadOne();
one.join();
ThreadTwo two = new ThreadTwo();
Thread threadTwo = new Thread(two);
threadTwo.join();
one.start();
threadTwo.start();
}
}
class ThreadOne extends Thread{
@Override
public void run(){
System.out.println("I am first thread,my name is "+Thread.currentThread().getName());
}
}
class ThreadTwo implements Runnable{
@Override
public void run(){
System.out.println("I am second thread,my name is "+Thread.currentThread().getName());
}
}
join使ThreadOne和TreadTwo依次顺序执行,其中的原理是什么,来看下Thread中的join方法:
public final void join() throws InterruptedException {
this.join(0L);
}
public final synchronized void join(long var1) throws InterruptedException {
long var3 = System.currentTimeMillis();
long var5 = 0L;
if (var1 < 0L) {
throw new IllegalArgumentException("timeout value is negative");
} else {
if (var1 == 0L) {
while(this.isAlive()) {
this.wait(0L);
}
} else {
while(this.isAlive()) {
long var7 = var1 - var5;
if (var7 <= 0L) {
break;
}
this.wait(var7);
var5 = System.currentTimeMillis() - var3;
}
}
}
}
synchronized线程锁,使得线程按照先后顺序进入,依次等待执行。进入等待队列后,线程执行顺序就确定了。