java 线程

以下代码,如何做才能使 end 一定是在t1,t2之后输出
public class Test{
public static void main(str[]arg2){
Thread t1=new Thread(new Runable(){
public void run(){
System.out.println("t1");
}
});
Thread t2=new Thread(new Runable(){
public void run(){
System.out.println("t2");
}
});
t1.start();
t2.start();
System.out.println("end");

 }

}

3个回答

在 t1.start();
t2.start();
后添加
t1.join();
t2.join();

还有是new Runnable

     Thread t1=new Thread(new Runnable(){ 
            public void run(){ 
                try {
                    Thread.sleep(6000);
                } catch (InterruptedException e) {
                }
                System.out.println("t1"); 
            } 
        }); 
        Thread t2=new Thread(new Runnable(){ 
            public void run(){ 
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                }
               System.out.println("t2"); 
            } 
        }); 
        t1.start(); 
        t2.start(); 
        t1.join();
        t2.join();
        System.out.println("end"); 

public static void main(String ars[]) {
Thread t1 = new Thread(new Runnable() {

        @Override
        public void run() {

            System.out.println("t1");

        }
    });
    Thread t2 = new Thread(new Runnable() {

        @Override
        public void run() {

            System.out.println("t2");

        }
    });
    t1.start();
    t2.start();
    while (t1.isAlive() || t2.isAlive()) {
    }  //等两个线程全部运行完成后输出
    System.out.println("end");

}

支持JamesZhao1987

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问