日期:2014-05-20  浏览次数:20714 次

线程优先的问题

我有两个方法 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();
     }
    }
 

------解决方案--------------------
引用:
Java code?1234567891011121314151617181920212223void fun2() {        Thread t = new Thread(new Runnable() {            public void run() {                for (int i = 0; i < 2; i++) {     ……