ITeye博客

对java线程join方法的理解

rokuan · 2011-05-26 09:31 · Java · 编程语言 · Java · thread · Markdown

先上代码:

public class ThreadA extends Thread {

	@Override
	public void run() {
		System.out.println("A start...");
		for (int i = 0; i < 10; i++) {
			try {
				Thread.sleep(1000);
				System.out.println("ta:"+i);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("A end...");
	}

}
public class ThreadB extends Thread {
	@Override
	public void run() {
		System.out.println("B start...");
		ThreadA t = new ThreadA();
		try {
			t.start();  //1
			t.join();
			for (int i = 0; i < 3; i++) {
				System.out.println(i);
			}
			System.out.println("B end...");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
public class Tst {
	public static void main(String[] args) {
		System.out.println("main start...");
		ThreadB b = new ThreadB();
		b.start();
		try {
			b.join();  //2
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("main end...");
	}
}

运行结果如下:

main start... B start... A start... ta:0 ta:1 ta:2 ta:3 ta:4 ta:5 ta:6 ta:7 ta:8 ta:9 A end... 0 1 2 B end... main end...

如果将注释标记1处的那行注释掉,则threadA不会启动,即join方法会检查线程是否启动,若未启动,则什么都不做。 若启动,则调用join的这个线程获得控制权,必须等这个线程结束后,才能继续当前线程的执行。 所以若将注释标记2处的那行注释掉,main线程将提早结束,不会等到threadB结束后再结束。而threadB并不会受main线程影响。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。