---
title: "Java多线程学习与总结(Join())"
author: "Dboyqiao"
date: "2010-10-29T20:47:48Z"
tags: []
categories: ["编程语言"]
slug: "java-join"
draft: false
lastmod: "2010-10-29T20:47:48Z"
id: 798015
url: "https://dboyqiao.iteye.com/blog/798015"
---

join()方法的用法：

    join()是主线程 等待子线程的终止。也就是在子线程调用了 join() 方法后面的代码，只有等到子线程结束了才能执行。

    例子如下：

 

```
public class Test implements Runnable {

	private static int a = 0;
	
	public void run() {
		
		for(int i=0;i<10;i++)
		{
			a = a + i;
		}
	}

	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {

		Thread t1 = new Thread(new Test());
		t1.start();
		//Thread.sleep(10);
		//t1.join();
		System.out.print(a);
		
	}
}
```

 上面程序最后的输出结果是0，就是当子线程还没有开始执行时，主线程已经结束了。

```
public class Test implements Runnable {

	private static int a = 0;
	
	public void run() {
		
		for(int i=0;i<10;i++)
		{
			a = a + i;
		}
	}

	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {

		Thread t1 = new Thread(new Test());
		t1.start();
		//Thread.sleep(10); 
                t1.join();
		System.out.print(a);
		
	}
}
```

 上面程序的执行结果是45，就是当主线程运行到t1.join()时，先执行t1，执行完毕后在执行主线程余下的代码！

    总结：join()方法的主要功能就是保证调用join方法的子线程先执行完毕再执行主线程余下的代码！