join的简单使用示例,通过构造函数,把b线程放到a线程之后,然后在a线程中使用b.join,实现简单的线程顺序完成
public class UseJoin {
public static void main(String[] args) {
WaitB b = new WaitB();
WaitA a = new WaitA(b);
a.start();
b.start();
}
}
class WaitA extends Thread {
private Thread thread;
public WaitA(Thread thread) {
this.thread = thread;
}
@Override
public void run() {
System.out.println("怪兽 开始排队");
if (thread != null) {
try {
System.out.println("奥特曼 插队");
thread.join();
Thread.sleep(2000);
System.out.println("怪兽买到到了东西");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class WaitB extends Thread {
@Override
public void run() {
System.out.println("奥特曼 在队列中了");
try {
Thread.sleep(2000);
System.out.println("奥特曼买到到了东西");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果
怪兽 开始排队
奥特曼 插队
奥特曼 在队列中了
奥特曼买到到了东西
怪兽买到到了东西