---
title: "对java线程join方法的理解"
author: "rokuan"
date: "2011-05-26T09:31:42Z"
tags: ["Java", "thread"]
categories: ["编程语言"]
slug: "java-join"
draft: false
lastmod: "2011-05-26T09:36:57Z"
id: 1059049
url: "https://rokuan.iteye.com/blog/1059049"
---

先上代码：

```java
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...");
	}

}
```


```java
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();
		}
	}
}
```


```java
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线程影响。