public class TestJoin {
public static void main(String[] args) {
MyThread2 t1 = new MyThread2("谢霆锋");
t1.start(); //启动分支线程
try {
t1.join(); //把T1分支线程合并到当前线程
} catch (InterruptedException e) {
}
for (int i = 1; i <= 5; i++) {
System.out.println("i am main thread");
}
}
}
class MyThread2 extends Thread {
public MyThread2(String s) { //定义成字符串String
super(s);
}
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("i am" + getName());
try {
sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
}
比较:yield方法和join方法
与yield方法相反的是join方法,它表示一直要等到指定的线程运行完毕,如:
try{ t.join();} catch (interruptedexception ignored) { }
表示要等到线程t运行完毕后,再执行下一步操作。这种情况比较少见。