Java线程join方法使用

话不多说,先上代码。

public class TestJoin {
	public static void main(String[] args) throws Exception{
		ThreadTestJoin t1=new ThreadTestJoin("小王");
		ThreadTestJoin t2=new ThreadTestJoin("小明");
		
		
		t1.start();
		t1.join();
		t2.start();
	}

}

public class ThreadTestJoin extends Thread{

	public ThreadTestJoin(String name) {
		super(name);
	}

	@Override
	public void run() {
		for(int i=0;i<10;i++){
			System.out.println(this.getName()+i);
		}
		
	}
}

join()//当我们调用某个线程的这个方法时,这个方法会挂起调用线程,直到被调用线程结束执行,调用线程才会继续执行

运行结果如下图所示:

然后测试join方法写在start方法前面会有如下结果:


结果证明,每次执行结果都是随机的,所以join方法必须在线程start方法调用之后调用才有意义。

  • 感谢您的阅读。如果文章感觉对您有用,麻烦您动动手指点个赞,以资鼓励。谢谢!

猜你喜欢

转载自blog.csdn.net/lihua5419/article/details/80676571