线程是用来执行异步程序的,但有时想让待待线程执行线束再向下执行其它操作,就是想把线程变成同步执行的,这时就需要用到Thread的join()方法了。
例如下面的代码:
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Wati 3 seconds.");
for (int i = 1; i <= 3; i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
t.start();
System.out.println("Main thread End.");
}
执行结果如下:
Main thread End.
Wati 3 seconds.
1
2
3
如果我想要让“Main thread End.”在最后打印,可在打印前调用t.join(),代码如下:
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Wati 3 seconds.");
for (int i = 1; i <= 3; i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Main thread End.");
}
执行结果为:
Wati 3 seconds.
1
2
3
Main thread End.