java多线程-线程间的通行之-join用法。

  • join的作用:
    多数情况下,主线程创建并启动子线程,如果子线程中要进行大量的耗时运算,主线程可能早于子线程结束之前结束。倘若子线程处理一个数据,主线程要取得这个数据中的值,就要用到join()方法,它的作用就是等待线程对象的销毁。
  • 源码
 public final void join() throws InterruptedException {
        join(0);
    }
public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {//等待该线程被销毁。
                wait(0);//
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

可以看到join()方法的内部是通过wait(long times)方法来实现线程等待的。所以他其实具备wait(long times)方法的特征。

  • 简单的例子
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Thread;

/**
 *
 * @author zjq
 */
public class join_1 extends Thread{
    
    @Override
    public void  run(){
        try {
            int secondValue = (int)(Math.random()*10000);
            System.out.println(secondValue);
            Thread.sleep(secondValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws InterruptedException {
        join_1 threadTest = new join_1();
        threadTest.start();
        threadTest.join();
        System.out.println("threadTest执行完毕后我再执行");
      
      
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39837953/article/details/84583796