---
title: "java Thread Join方法学习（同步）（等待调用join的线程先执行）"
author: "艾伦蓝"
date: "2016-03-15T10:09:39Z"
tags: []
categories: ["编程语言"]
slug: "java-thread-join-join"
draft: true
lastmod: "2017-08-07T09:20:08Z"
id: 2283072
url: "https://forlan.iteye.com/blog/2283072"
---

**<span style="color:red">join() 方法主要是让调用该方法的线程完成run方法里面的东西后，再执行join()方法后面的代码。</span>**


```java

class ThreadTesterA implements Runnable {
 
    private int counter;
 
    @Override
    public void run() {
        while (counter <= 10) {
            System.out.print("Counter = " + counter + " ");
            counter++;
        }
        System.out.println();
    }
}
 
class ThreadTesterB implements Runnable {
 
    private int i;
 
    @Override
    public void run() {
        while (i <= 10) {
            System.out.print("i = " + i + " ");
            i++;
        }
        System.out.println();
    }
}
 
public class ThreadTester {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new ThreadTesterA());
        Thread t2 = new Thread(new ThreadTesterB());
        t1.start();
        t1.join(); // wait t1 to be finished
        t2.start();
        t2.join(); // in this program, this may be removed
    }
}

```



```java

package  mythread;

public   class  JoinThread  extends  Thread
{
     public   static int  n  =   0 ;

     public static   synchronized   void  inc(){
        n ++ ;
    }
     public   void  run(){
         for  ( int  i  =   0 ; i  <   10 ; i ++ )
             try 
            {
                inc();  //  n = n + 1 改成了 inc(); 
                sleep( 3 );  //  为了使运行结果更随机，延迟3毫秒 

            }
             catch  (Exception e)
            {
            }
    }

     public   static   void  main(String[] args)  throws  Exception{

        Thread threads[]  =   new  Thread[ 100 ];
         for  ( int  i  =   0 ; i  <  threads.length; i ++ )
             //  建立100个线程 
            threads[i]  =   new  JoinThread();
         for  ( int  i  =   0 ; i  <  threads.length; i ++ )
             //  运行刚才建立的100个线程 
            threads[i].start();
         for  ( int  i  =   0 ; i  <  threads.length; i ++ )
             //  100个线程都执行完后继续 必须加上join方法
            threads[i].join();  
        System.out.println( " n= "   +  JoinThread.n);
    }
} 

```


**<span style="color:blue">join方法的功能就是使异步执行的线程变成同步执行。</span>**也就是说，当调用线程实例的start方法后，这个方法会立即返回，<span style="color:red">如果在调用start方法后后需要使用一个由这个线程计算得到的值，就必须使用join方法。</span>如果不使用join方法，就不能保证当执行到start方法后面的某条语句时，这个线程一定会执行完。而使用join方法后，直到这个线程退出，程序才会往下执行。