问题描述
以下代码,如何做才能使 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"); }}
解决方案
在 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");
解决方案二:
支持JamesZhao1987
解决方案三:
public static void main(String ars[]) {Thread t1 = new Thread(new Runnable() {@Overridepublic void run() {System.out.println("t1");}});Thread t2 = new Thread(new Runnable() {@Overridepublic void run() {System.out.println("t2");}});t1.start();t2.start();while (t1.isAlive() || t2.isAlive()) {} //等两个线程全部运行完成后输出System.out.println("end");}