Thread.join()

阅读更多

Thread的非静态方法join()让一个线程t2“加入”到另外一个线程t1的尾部。在A执行完毕之前,B不能执行

 

 

分别注释t1.join()和t2.join()观察程序打印顺序

 

class ThreadTesterA implements Runnable {
	private int i;
	public void run() {
		try {
			while (i <= 10) {
				System.out.println("ThreadTesterA = " + i + " ");
				Thread.sleep(500);
				i++;
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class ThreadTesterB implements Runnable {
	private int i;
	public void run() {
		try {
			while (i <= 10) {
				System.out.println("ThreadTesterB = " + i + " ");
				Thread.sleep(500);
				i++;
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

public class MyThread {
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread(new ThreadTesterA());
		Thread t2 = new Thread(new ThreadTesterB());
		
		System.out.println("准备执行线程");
		t1.start();
		System.out.println("已经启动线程t1");
		
		t1.join(); // 等待线程t1执行完时才向下执行

		t2.start();
		System.out.println("已经启动线程t2");
		t2.join(); // 等待线程t2执行完时才向下执行

		System.out.println("总线程执行结束");
	}
}

 

程序执行结果:

准备执行线程
已经启动线程t1
ThreadTesterA = 0
ThreadTesterA = 1
ThreadTesterA = 2
ThreadTesterA = 3
ThreadTesterA = 4
ThreadTesterA = 5
ThreadTesterA = 6
ThreadTesterA = 7
ThreadTesterA = 8
ThreadTesterA = 9
ThreadTesterA = 10
已经启动线程t2
ThreadTesterB = 0
ThreadTesterB = 1
ThreadTesterB = 2
ThreadTesterB = 3
ThreadTesterB = 4
ThreadTesterB = 5
ThreadTesterB = 6
ThreadTesterB = 7
ThreadTesterB = 8
ThreadTesterB = 9
ThreadTesterB = 10
线程执行结束

你可能感兴趣的:(thread,join)