给定三个线程,线程名分别为A、B、C。每个线程业务是打印名称,要求打印结果为ABC
思路:线程执行顺序是A线程执行,B线程执行,C线程执行。即:B线程中调用A.join(),C线程中调用B.join()
join方法
作用:暂停当前线程,等待子线程执行结束当前线程才能执行。join方法让并行的线程合并为串行的线程执行
例如:a线程中执行代码b.join()方法,则a线程会停止当前执行,并让b线程线执行,直到b线程执行结束,a线程才继续执行
public class ABCThread extends Thread{
private Thread thread;
private String name;
public ABCThread(Thread thread, String name) {
this.thread = thread;
this.name = name;
}
@Override
public void run() {
try {
if(thread != null) thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name);// 打印线程名
}
public static void main(String[] args) {
ABCThread a = new ABCThread(null, "A");
ABCThread b = new ABCThread(a, "B");
ABCThread c = new ABCThread(b, "C");
a.start();
b.start();
c.start();
}
}