Java多线程-join()线程加入

本文介绍了Java中join()方法的作用,包括其等待线程终止的三种形式,以及线程加入的概念。join()使得主线程在执行完特定代码后等待子线程结束,确保了线程间的有序执行。通过示例代码展示了未使用和使用join()时的不同运行结果,强调了在需要依赖子线程结果时join()的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一)join()简介

void join():等待这个线程终止。

void join(long millis):等待这个线程终止最多 millis毫秒。

void join(long millis, int nanos):等待最多 millis毫秒加上 nanos纳秒这个线程终止。

 

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

线程加入:在当前线程调用join方法时,会使线程变为阻塞状态,直到另一线程运行结束,当前线程阻塞状态变为就绪状态。

适用场景:当主线程启动子线程时,如子线程计算耗时比较久,主线程会优先子线程结束,但当主线程处理完事务,需要用到子线程的处理结果,该场景就需要等待子线程结束,再执行主线程。

 

二)join()

jdk中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) { // 指定毫秒数小于0时, 抛异常
        throw new IllegalArgumentException("timeout value is negative");
    }

    if (millis == 0) { // 当毫秒数为0时
        while (isAlive()) { // 判断线程是否属于激活状态
            wait(0); // 一直等待
        }
    } else {
        while (isAlive()) {
            long delay = millis - now;
            if (delay <= 0) {
                break;
            }
            wait(delay);
            now = System.currentTimeMillis() - base;
        }
    }
}

public final synchronized void join(long millis, int nanos) throws InterruptedException {
    if (millis < 0) { // 指定毫秒数小于0时, 抛异常
        throw new IllegalArgumentException("timeout value is negative");
    }

    if (nanos < 0 || nanos > 999999) {
        throw new IllegalArgumentException("nanosecond timeout value out of range");
    }

    if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
        millis++;
    }

    join(millis); // 指定毫秒数
}

 

join()案例

public class JoinRunnable implements Runnable {
	
    private Thread thread;
    private String threadName;
    public JoinRunnable(String threadName) {
        this.threadName = threadName;
    }
	
    public void run() {
        try {
            for(int i=0; i<5; i++) {
                System.out.println("Thread Name: " + threadName + ", i = " + i);
				
                Thread.sleep((int)(Math.random()*100));
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
	
    public void start() {
        if (thread == null) {
            thread = new Thread(this, threadName);
            thread.start();
        }
    }
	
    public void join() {
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

未使用join()时:

public class Main {

    public static void main(String[] args) {
        System.out.println("-->main主线程启动");
        JoinRunnable r1 = new JoinRunnable("A");
        JoinRunnable r2 = new JoinRunnable("B");
        r1.start();
        r2.start();
        System.out.println("-->main主线程结束");
    }
}

运行结果:

结果说明:当程序启动时,启动了一个main线程,两个AB子线程,main线程优先子线程执行完。

 

使用join()时:

public class Main {

    public static void main(String[] args) {
        System.out.println("-->main主线程启动");
        JoinRunnable r1 = new JoinRunnable("A");
        JoinRunnable r2 = new JoinRunnable("B");
        r1.start();
        r2.start();
		
        r1.join();
        r2.join();
        System.out.println("-->main主线程结束");
    }
}

运行结果:

结果说明:当程序启动时,启动了一个main线程,两个AB子线程,由于子线程调用了join()方法,所以主线程会等待子线程执行完之后才执行。

 

识别二维码关注个人微信公众号

本章完结,待续,欢迎转载!
 
本文说明:该文章属于原创,如需转载,请标明文章转载来源!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值