我有两个方法 fun1和fun2,在fun1中调用了fun2,在fun2中开了一个线程(很耗时间的线程),我现在想让fun2运行完了之后,再继续运行fun1,应该怎么做?求指点。
如下代码:
我要的输出结果为:
fun2
fun2
fun1
应该怎么做?
package thread;public class ThTest { void fun1() {
fun2();
System.out.println("fun1");
}
void fun2() {
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 2; i++) {
System.out.println("fun2");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} }).start(); } public static void main(String[] args) {
ThTest th = new ThTest();
th.fun1();
}
}
void fun2() {
Thread t = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 2; i++) {
System.out.println("fun2");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
t.start();
try{
t.join();
}catch(Exception e){
e.printStackTrace();
}
}
join() 方法:它能够使调用该方法的线程在此之前执行完毕。