java中Thread类的join方法

单核cpu运行多线程时底层实现原理是多个线程间切换,由于cpu的处理速度很快,看上去像多个线程同时运行。那么我们如何实现让线程T1,T2,T3,在T1执行完成后才执行T2,T2执行完成后才执行T3,也就是线程的串行化,通过Thread类的join方法就可以实现。

join方法:将该线程加入当前线程,当前线程等待加入线程执行完成才继续执行。
例子:
public class ThreadJoinTest implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new ThreadJoinTest());
thread.start();
thread.join();
System.out.println("主线程结束");
}

@Override
public void run() {
System.out.println("子线程开始");
for(int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
}
System.out.println("子线程结束");
}
}
执行结果:
java中Thread类的join方法_第1张图片
join(long  millis)方法:将该线程加班当前线程,当前线程等待加入线程millis时间,当达到millis时间后不管加入线程是否完成,当前线程都继续执行,若加入线程在小于millis时间执行完成,则当前线程等待时间等于加入线程的执行时间。
例子:
public class ThreadJoinTest implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new ThreadJoinTest());
thread.start();
thread.join(2000);
System.out.println("主线程结束");
}

@Override
public void run() {
System.out.println("子线程开始");
for(int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
}
System.out.println("子线程结束");
}
}
执行结果:
java中Thread类的join方法_第2张图片

你可能感兴趣的:(java)