join主要为让多线程按顺序执行
源码:wait-notify-synchronized
public class Thread008 implements Runnable{
public static void main(String[] args){
//主线程调用t1.join 主线程阻塞且释放锁
//必须等待t1线程执行完的情况下 主线程才能继续执行
try{
Thread t1=new Thread(new Thread008(),"T1");
Thread t2=new Thread(new Thread008(),"T2");
Thread t3=new Thread(new Thread008(),"T3");
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
t3.join();
for(int j=0;j<20;j++){
System.out.println(Thread.currentThread().getName()+","+j);
}
}catch (Exception e){
}
}
@Override
public void run() {
for(int i=0;i<20;i++){
System.out.println(Thread.currentThread().getName()+","+i);
}
}
}
public class Thread008 implements Runnable{
Thread t;
public Thread008(Thread thread) {
this.t = thread;
}
public static void main(String[] args){
//主线程调用t1.join 主线程阻塞且释放锁
//必须等待t1线程执行完的情况下 主线程才能继续执行
try{
Thread t1=new Thread(new Thread008(null),"T1");
Thread t2=new Thread(new Thread008(t1),"T2");
Thread t3=new Thread(new Thread008(t2),"T3");
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
for(int j=0;j<20;j++){
System.out.println(Thread.currentThread().getName()+","+j);
}
}catch (Exception e){
}
}
@Override
public void run() {
try {
if(t!=null){
t.join();
}
}catch (Exception e){
}
for(int i=0;i<20;i++){
System.out.println(Thread.currentThread().getName()+","+i);
}
}
}