Thread.join() 的使用和例子

 void join()  Waits for this thread to die. 
 void join(long millis)  Waits at most millis milliseconds for this thread to die. 
 void join(long millis, int nanos)  Waits at most millis milliseconds plus nanos nanoseconds for this thread to die. 


Thread.join()应该是让当前线程block住,等线程执行完之后,再继续执行,而且可以设置让当前线程等待的时间,如果超过时间,不用等当前线程执行完,就可以继续执行 。 比如有3个线程在执行计算任务,必须等三个线程都执行完才能汇总,那么这时候在主线程里面让三个线程join,最后计算结果既可。

package thread;

import java.util.Random;

public class TestThreadJoin {
    public static void main(String[] args) {
        CounterThread[] counter = new CounterThread[5];
        Thread c;
        long l = System.currentTimeMillis();
        for (int i = 0; i < counter.length; i ++) {
            counter[i] = new CounterThread();
            c = new Thread(counter[i], "counter " + i);
            c.start();
            try {
                c.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("all time  = " + (System.currentTimeMillis() - l) + " ms");
        int result = 0; 
        for (CounterThread re : counter) {
            result += re.getResult();
        }
        System.out.println("result = " + result);
    }
}
class CounterThread implements Runnable {
    int result ;
    
    public int getResult() {
        return result;
    }

    public void setResult(int result) {
        this.result = result;
    }

    @Override
    public void run() {
        int time = (new Random().nextInt() >>> 1) % 5000;
        try {
            Thread.sleep(time);
            System.out.println(Thread.currentThread().getName() + " sleep " + time + " ms");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        result = 5;
    }
    
}


执行结果:
counter 0 sleep 44 ms
counter 1 sleep 1161 ms
counter 2 sleep 4782 ms
counter 3 sleep 4264 ms
counter 4 sleep 3313 ms
all time  = 13578 ms
result = 25


当设置
c.join(1000);
后,执行结果如下:
counter 0 sleep 93 ms
counter 2 sleep 864 ms
counter 1 sleep 3193 ms
all time  = 3969 ms
result = 15
counter 3 sleep 3639 ms
counter 4 sleep 4806 ms




你可能感兴趣的:(java,thread)