Java多线程之join()方法

join()方法能让其他线程从运行状态变为阻塞状态,直到当前线程执行完成后,其他线程才会执行。

起初我对这句话理解是有误的,还好及时更正了过来。看下代码

public class Test implements Runnable {
    private String threadName;

    public Test(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println(threadName + i);
        }
    }

    public static void main(String[] args) {
        Test test1 = new Test("线程1*");
        Test test2 = new Test("线程2$");
        Thread thread1 = new Thread(test1);
        Thread thread2 = new Thread(test2);
        thread1.start();
        thread2.start();
        try {
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

我预想的结果是线程1先启动,然后执行一部分,线程2启动了,然后调用了join方法,此时线程1等待线程2执行完成后继续执行剩余部分。但是上面程序运行的结果是两个线程交替执行,并没有出现线程1等待线程2的情况。

我们把线程1的启动挪到线程2join方法后再看看

public class Test implements Runnable {
    private String threadName;

    public Test(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println(threadName + i);
        }
    }

    public static void main(String[] args) {
        Test test1 = new Test("线程1*");
        Test test2 = new Test("线程2$");
        Thread thread1 = new Thread(test1);
        Thread thread2 = new Thread(test2);
        thread2.start();
        try {
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread1.start();
    }
}

这次并没有出现线程1和线程2交替执行的情况。

所以join方法应该这么解释:

A.join()方法之后的线程(包括主线程)会等待A线程执行结束后再执行,A线程之前的线程并不会等待A执行后再执行,而是交替执行

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值