会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 133308个问题
JAVA 全系列/第二阶段:JAVA 基础深化和提高/容器 346楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/容器 347楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/IO流技术 348楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/容器 350楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/容器 351楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/容器 352楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/多线程技术 354楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/多线程技术 356楼

class A implements Runnable{
    private Thread b;
    public A(Thread b){
        this.b=b;
    }

    @Override
    public void run() {
        for (int i=0;i<10;i++){
            System.out.println(Thread.currentThread().getName()+" A "+i);
            if (i==6){
                try {
                    b.join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

class B implements Runnable{

    @Override
    public void run() {
        for (int i =0;i<20;i++){
            System.out.println(Thread.currentThread().getName()+" B "+i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
public class TestJoinThread{
    public static void main(String[] args) {
        Thread t1 = new Thread(new A(t));
        Thread t = new Thread(new B());
        t1.start();
        t.start();
        for (int i=0;i<10;i++){
            System.out.println(Thread.currentThread().getName()+" 主线程 "+i);
            if (i==4){
                try {
                    t1.join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
Thread t1 = new Thread(new A(t));
        Thread t = new Thread(new B());

为什么写成这样报错,不都是把B给A里了吗

Thread t1 = new Thread(new B());
        Thread t = new Thread(new A(t1));

视频是这样的

还有为什么要先创建线程B的对象

JAVA 全系列/第二阶段:JAVA 基础深化和提高/多线程技术 357楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637