java,让线程按照顺序执行

目录

join源码如下:

测试代码如下:


自己写了一段main方法代码,试验过N次,暂时未发现问题。

自己的理解(如果错误,请大佬们指导一下):

使用线程的join方法,让线程进行等待,join()方法实际跟调用join(0)效果一致,参数代表的是等待线程执行的时间,单位是毫秒。

设置为0并不代表不等待,而是一直等待,直到调用isAlive方法返回true,表示当前线程执行完成;否则继续等待(串发执行)。

如果设置的等待时间为负数,直接报错,如果为正数,前一个线程会等待xx.join的xx这个线程正数的时间后继续执行(并发执行)。

join源码如下:

join()方法

public final void join() throws InterruptedException {
    join(0);
}

join(long)方法

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;
        }
    }
}

测试代码如下:

public static void main(String[] args) {
    Thread t1 = new Thread(() ->{
        for (int i =0; i < 10; i++) {
            System.out.println("I‘m Thread one:" + i);
        }
    });

    Thread t2 = new Thread(() -> {
        try {
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i =0; i < 10; i++) {
            System.out.println("I‘m Thread two:" + i);
        }
    });

    Thread t3 = new Thread(() -> {
        try {
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i =0; i < 10; i++) {
            System.out.println("I‘m Thread three:" + i);
        }
    });

    t1.start();
    t3.start();
    t2.start();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值