java多线程 关于join 的问题
高洛峰
高洛峰 2017-04-18 10:34:56
[Java讨论组]

我想通过join让线程 a b c d顺序打印,但是现在是乱序打印

public class ExJoin extends Thread {

    Thread thread;

    public ExJoin(){

    }

    public ExJoin(Thread thread){
        this.thread  = thread;
    }

    @Override
    public void run() {
        try {
            if (thread != null){
                thread.join();
            }
            System.out.println(Thread.currentThread().getName()+"  is running");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Thread threadA = new ExJoin();
        threadA.setName("A");
        Thread threadB = new ExJoin(threadA);
        threadB.setName("B");
        Thread threadC = new ExJoin(threadB);
        threadC.setName("C");
        Thread threadD =  new ExJoin(threadC);
        threadD.setName("D");


        threadC.start();
        threadD.start();
        threadA.start();
        threadB.start();
    }
}
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(3)
巴扎黑

在run方法里加个sleep试试。

PHP中文网

按照楼主的代码逻辑,join是无法做到有序的,因为A/B/C/D线程的启动运行依赖于CPU调度,如果线程B未启动线程C调用threadB.join方法是不会生效的。可以看看jdk内置的逻辑实现isAlive()false时直接返回了。

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;
        }
    }
}
PHP中文网

run方法中sleep(1000)确实会顺序出现。我猜测可能是指令重排序,前面的线程已经就绪,但是后面的线程对象还没有创建出来,所以出现了乱序。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号