---
title: "Thread.join()的用法"
author: "java-admin"
date: "2009-07-16T15:37:02Z"
tags: ["ASP", "BBS", "J#", "thread"]
slug: "thread-join"
draft: false
lastmod: "2009-07-16T15:37:02Z"
id: 427177
url: "https://java-admin.iteye.com/blog/427177"
---

原文：http://www.j2medev.com/bbs/dispbbs.asp?boardid=3&Id=34846

 

 thread.join()应该是让当前线程block住，等thread执行完之后，再继续执行 。比如有3个线程在执行计算任务，必须等三个线程都执行完才能汇总，那么这时候在主线程里面让三个线程join，最后计算结果既可。代码显示如下。

import java.util.Random;

public class ThreadTest {

    public static void main(String\[] args) {  
        System.out.println("in " + Thread.currentThread().getName());  
        long start = System.currentTimeMillis();  
        CounterThread\[] ct = new CounterThread\[3];  
        for (int i = 0; i &lt; ct.length; i++) {  
            ct\[i] = new CounterThread();  
            ct\[i].start();  
            try {  
                ct\[i].join();  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  
        long end = System.currentTimeMillis();  
        System.out.println("join total time = " + (end - start));  
        int result = 0;  
        for (int j = 0; j &lt; ct.length; j++) {  
            result += ct\[j].getResult();  
        }  
        System.out.println("the result is " + result);

    }

}

class CounterThread extends Thread {

    public CounterThread() {  
    }

    private int result;

    public int getResult() {  
        return result;  
    }

    public void run() {  
        try {  
            int time = (new Random().nextInt() &gt;&gt;&gt; 1) % 5000;  
            Thread.sleep(time);  
            System.out.println(Thread.currentThread().getName()  
                    + " is blocked for " + time + "ms");  
        } catch (InterruptedException ex) {

        }  
        result = 5;  
    }  
}

输出结果：

in main  
Thread-0 is blocked for 205ms  
Thread-1 is blocked for 4226ms  
Thread-2 is blocked for 4469ms  
join total time = 8906  
the result is 15