ITeye博客

join 只能阻塞当前线程,不能阻塞其它并行线程

dmwdmc · 2013-06-17 21:35 · 线程 · 编程语言 · Markdown

join 会阻塞当前线程,会强制完其自己的线程后,再释放当前线程的阻塞。 但是它并不阻塞其他线程。

public class ThreadTest {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Thread t1=new SleepThread("t1");
		Thread t2=new SleepThread("t2");
		t1.start();
		t2.start();
		try {
			t1.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("mainend...");
	}
}

public class SleepThread extends Thread{
	private String t;
	public SleepThread(String t){
		this.t=t;
	}
	@Override
	public void run() {
		try {
				System.out.println(t+"sleep start");
				for(int i=0;i<5;i++){
					Thread.sleep(1000);
					System.out.println(t+"run");
				}
				System.out.println(t+"sleep end");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

输出结果是: t1sleep start t2sleep start t2run t1run t2run t1run t1run t2run t1run t2run t1run t1sleep end mainend... t2run t2sleep end

评论(0)

暂无评论。

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