java多线程join方法

                                        java多线程join方法

java中多线程是异步执行的,我们想要多线程按照一定的顺序执行,需要加锁,或者在其他线程start之前加join。

来看看实例:

package Test;

public class ThreadNum extends Thread{

	private int first;
	
	public ThreadNum(String name,int first) {
		
		super(name);
		
		this.first=first;
	}
	
	public void run() {
		System.out.print("当前执行线程是:"+this.getName()+"  ");
		for(int i=first;i<20;i+=2) {
			System.out.print(i+"\t");
		}
		System.out.println(this.getName()+"结束");
	}
	
	public static void main(String[] args) {
		
		System.out.println("当前的线程是"+Thread.currentThread().getName());
		ThreadNum odd=new ThreadNum("奇数线程", 1);
		ThreadNum even=new ThreadNum("偶数线程", 2);
		odd.setPriority(1);
		odd.start();
		try {
			odd.join();
		} catch (InterruptedException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		even.start();
		try {
			odd.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			even.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("当前活动的线程是"+Thread.activeCount());
	}

}

如果不在奇数线程start后面偶数线程start之前加join,奇偶线程就会交替执行。

join是在一个线程start之后,在其他线程start之前用。这样就达到了同步执行线程的目的。

线程在调用join之后,会让其他线程包括主函数的线程也会停止运行。

如果其他join写在了其他线程之后,不会影响其他线程的异步执行。

猜你喜欢

转载自blog.csdn.net/qq_43279637/article/details/84421878