多线程:join()方法

Join()方法

当前线程暂停执行,新加入的线程开始执行,当新线程执行完之后,再执行当前线程。

MyThread.java

package test4;

public class MyThread extends Thread {
	String name;

	public MyThread(String name) {
		super();
		this.name = name;
	}
	public void run() {
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} //休眠5秒
		
		System.out.println("线程"+this.name+"执行结束");
	}

}

text1.java

package test4;
public class test {
         public static void main(String[] args) {
		MyThread mt1=new MyThread("123");
		MyThread mt2=new MyThread("zaa");
		
		mt1.start();
		mt2.start();
		
		System.out.println("程序结束");
	}
}

先输出“程序结束”,停留5秒后,在输出

线程zaa执行结束
线程123执行结束

不用join


text2.java

package test4;

public class test2 {

	public static void main(String[] args) throws InterruptedException {
		MyThread mt1=new MyThread("123");
		MyThread mt2=new MyThread("zaa");
		
		mt1.start();
		mt2.start();
		
		mt1.join();
		mt2.join();
		
		System.out.println("程序结束");
	}
}

5秒后输出:

线程zaa执行结束
线程123执行结束
程序结束

使用join

 

阅读剩余
THE END