Java使用obj.threadobj.join抛出错误

Java使用obj.threadobj.join抛出错误,java,multithreading,exception,compiler-errors,Java,Multithreading,Exception,Compiler Errors,我希望子线程在主线程继续其操作之前完成 在启动线程之后,我调用了join,我认为它会在继续主线程之前完成子线程,但抛出了一些错误,我不明白它为什么会抛出错误 以下是我的代码: class FirstThread implements Runnable{ Thread t; String threadname; FirstThread(String name){ threadname = name; t = new Thread(this,t

我希望子线程在主线程继续其操作之前完成

在启动线程之后,我调用了
join
,我认为它会在继续主线程之前完成子线程,但抛出了一些错误,我不明白它为什么会抛出错误

以下是我的代码:

class FirstThread implements Runnable{
    Thread t;
    String threadname;
    FirstThread(String name){
        threadname = name;
        t = new Thread(this,threadname);
        System.out.println(name+" Starting");
        t.start();
    }
    public void run(){
        try{
            for(int i=0; i < 5; i++){
                System.out.println(threadname+" : "+ i);
                Thread.sleep(500);
            }
        }catch(InterruptedException e){
            System.out.println("Exception: "+ e);
        }
    }

}

public class ThreadJoin {

    public static void main(String args[]){
        System.out.println("Starting child Thread");
        FirstThread ft = new FirstThread("new thread");
        ft.t.join();
        try{
            for(int i =0; i < 5; i++){
                System.out.println("Main : "+i);
                Thread.sleep(1000);
            }

        }catch(InterruptedException e){
            System.out.println("Exception : "+ e);
        }

    }

}
使用
ft.t.join
创建新线程并使其首先完成

但它抛出了一个错误:

线程“main”java.lang中出现异常。错误:未解析编译 问题:未处理的异常类型InterruptedException

位于ThreadJoin.main(ThreadJoin.java:29)

第29行

ft.t.连接()

如果我删除上面的行,它可以正常工作。

声明它抛出一个
中断异常。你必须以某种方式处理它——要么让打电话的人也扔它,要么抓住它。只需将有问题的行移到
catch
块中,就可以了:

try {
    ft.t.join(); // Here!
    for (int i =0; i < 5; i++) {
        System.out.println("Main : "+i);
        Thread.sleep(1000);
    }
} catch(InterruptedException e){
    System.out.println("Exception : "+ e);
}
试试看{
ft.t.join();//这里!
对于(int i=0;i<5;i++){
System.out.println(“Main:+i”);
睡眠(1000);
}
}捕捉(中断异常e){
System.out.println(“异常:+e”);
}

非常感谢您在尝试执行程序之前是否考虑过修复编译错误?我知道为什么这个问题值得投反对票
try {
    ft.t.join(); // Here!
    for (int i =0; i < 5; i++) {
        System.out.println("Main : "+i);
        Thread.sleep(1000);
    }
} catch(InterruptedException e){
    System.out.println("Exception : "+ e);
}