package fighting;
public class ThreadJoin {
/**
* join方法:
* 当A线程执行到了B线程的join方法时,A就会等待,等B线程都执行完,A才会执行。
*
* join方法可以用来临时加入线程执行。
*
*/
public static void main(String[] args) throws InterruptedException {
JoinDemo jd = new JoinDemo();
Thread t1 = new Thread(jd);
Thread t2 = new Thread(jd);
t1.start();
//① t1.join();//主线程往下执行的过程中,t1要申请加入的运行的线程,也就是申请cpu执行权,这时主线程就会处于冻结状态了。t1就开始执行了,t1就循环70次,t1结束后主线程才会执行。
//一个线程在运行过程中,临时加入一个线程,等这个线程执行完,原线程再继续执行。
t2.start();
//② t1.join();//这句话放在这里,当主线程执行到这里,就会释放执行权,而这时t1、t2都是运行状态,这时t1、t2就会交替执行,等t1执行完了,不管t2是否执行完,主线程就会继续执行。
for(int x=0;x<15;x++){
System.out.println("main..."+x);
}
System.out.println("over");
}
}
class JoinDemo implements Runnable{
public void run() {
for(int x=0;x<10;x++){
System.out.println(Thread.currentThread().getName()+"..."+x);
}
}
}
没有join方法的执行结果:3个线程交替执行
main...0
Thread-1...0
Thread-0...0
main...1
Thread-1...1
Thread-0...1
main...2
Thread-1...2
Thread-0...2
main...3
Thread-1...3
Thread-0...3
main...4
Thread-1...4
Thread-0...4
main...5
Thread-1...5
Thread-0...5
main...6
Thread-1...6
Thread-0...6
main...7
Thread-1...7
Thread-0...7
main...8
Thread-1...8
Thread-0...8
main...9
Thread-1...9
Thread-0...9
main...10
main...11
main...12
main...13
main...14
over
①的执行结果:t1执行完了,主线程继续执行。
Thread-0...0
Thread-0...1
Thread-0...2
Thread-0...3
Thread-0...4
Thread-0...5
Thread-0...6
Thread-0...7
Thread-0...8
Thread-0...9
main...0
Thread-1...0
main...1
Thread-1...1
main...2
Thread-1...2
main...3
Thread-1...3
main...4
Thread-1...4
main...5
Thread-1...5
main...6
Thread-1...6
main...7
Thread-1...7
main...8
Thread-1...8
main...9
Thread-1...9
main...10
main...11
main...12
main...13
main...14
over
②的执行结果:t1,t2交替执行,等t1执行完了,主线程继续执行。
Thread-0...0
Thread-0...1
Thread-0...2
Thread-1...0
Thread-0...3
Thread-1...1
Thread-0...4
Thread-1...2
Thread-0...5
Thread-1...3
Thread-0...6
Thread-1...4
Thread-0...7
Thread-1...5
Thread-0...8
Thread-0...9
Thread-1...6
Thread-1...7
Thread-1...8
Thread-1...9
main...0
main...1
main...2
main...3
main...4
main...5
main...6
main...7
main...8
main...9
main...10
main...11
main...12
main...13
main...14
over