join()方法作用就是:当一个线程中调用另一个线程的join()方法时,当前线程会等待另一个线程执行完毕后,在继续执行。起到一种同步的作用。即:若线程A调用线程B的join()方法,那么A会等到B的run()中内容执行完毕再去执行A的run 方法。
package com.zhiru;
class TA implements Runnable {
private int count = 0;
@Override
public void run() {
//启动线程TA
System.out.println(Thread.currentThread().getName()+"start...");
while (count <= 10) {
System.out.print("count=" + count + " ");
count++;
}
System.out.print("\n");
}
}
class TB implements Runnable {
private int id = 0;
private Thread c;
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName()+"start...");
c=new Thread(new TC());//创建线程TC的对象
try {
c.start();
c.join();//加入线程TC,直到线程TC中的run内容执行完在执行TB的。
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (id++ <= 10) {
System.out.print("id=" + id + " ");
}
System.out.print("\n");
}
}
class TC implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("TC was called!"+Thread.currentThread().getName()+"start...");
for(int i=1;i<=10;i++) System.out.print(i+" ");
System.out.print("\n");
}
}
public class ThreadJoin {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Thread t2=new Thread(new TB());
Thread t1=new Thread(new TA());
t2.start();
t2.join();//直到线程t2执行完在执行t1.
t1.start();
// t1.join();
}
}
Thread-0start...
TC was called!Thread-2start...
1 2 3 4 5 6 7 8 9 10
id=1 id=2 id=3 id=4 id=5 id=6 id=7 id=8 id=9 id=10 id=11
Thread-1start...
count=0 count=1 count=2 count=3 count=4 count=5 count=6 count=7 count=8 count=9 count=10