join()
方法意味着等待当前线程执行完,主线程才能继续往下执行。 也就是将当前线程加入到主线程中。
例如下面的例子:我们将ts1
加入到主线程,看看会发生什么结果?
package testthread;
public class TestStart extends Thread{
String name;
public TestStart(String name) {
this.name = name;
}
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始");
for(int i = 0; i<10; i++) {
System.out.println(name+"运行"+i);
try {
Thread.sleep((int) Math.random()*10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"线程结束");
}
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"线程开始");
// TODO Auto-generated method stub
TestStart ts1 = new TestStart("A");
TestStart ts2 = new TestStart("B");
ts1.start();
try {
ts1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
ts2.start();
System.out.println(Thread.currentThread().getName()+"线程结束");
}
}
运行结果如下:
main线程开始
Thread-0线程开始
A运行0
A运行1
A运行2
A运行3
A运行4
A运行5
A运行6
A运行7
A运行8
A运行9
Thread-0线程结束
main线程结束
Thread-1线程开始
B运行0
B运行1
B运行2
B运行3
B运行4
B运行5
B运行6
B运行7
B运行8
B运行9
Thread-1线程结束
Thread-0
等价于A
,Thread-1
等价于B
。ts1
使用join()
方法之后,main
开始之后等待Thread-0
结束。由于ts2
没有使用join()
方法,所以最后执行。下来再看看给ts2
使用join()
方法之后是什么结果?
package testthread;
public class TestStart extends Thread{
String name;
public TestStart(String name) {
this.name = name;
}
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始");
for(int i = 0; i<10; i++) {
System.out.println(name+"运行"+i);
try {
Thread.sleep((int) Math.random()*10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"线程结束");
}
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"线程开始");
// TODO Auto-generated method stub
TestStart ts1 = new TestStart("A");
TestStart ts2 = new TestStart("B");
ts1.start();
try {
ts1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
ts2.start();
try {
ts2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"线程结束");
}
}
运行结果如下:
main线程开始
Thread-0线程开始
A运行0
A运行1
A运行2
A运行3
A运行4
A运行5
A运行6
A运行7
A运行8
A运行9
Thread-0线程结束
Thread-1线程开始
B运行0
B运行1
B运行2
B运行3
B运行4
B运行5
B运行6
B运行7
B运行8
B运行9
Thread-1线程结束
main线程结束
现在Thread-0
、Thread-1
都加入到主线程中了,所以得等这两个子线程结束之后才能继续完成main
线程。那我们再来看看ts1
和ts2
线程对象都不使用join()
,会是什么样?下面是结果:
main线程开始
main线程结束
Thread-0线程开始
Thread-1线程开始
B运行0
A运行0
B运行1
A运行1
B运行2
A运行2
B运行3
B运行4
A运行3
B运行5
A运行4
A运行5
B运行6
A运行6
A运行7
A运行8
B运行7
A运行9
B运行8
Thread-0线程结束
B运行9
Thread-1线程结束
从结果可以看出,不加的话主线程mian
不会等Thread-0
、Thread-1
结束,会继续运行,所以我们看到了main
线程结束的打印。