gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:08:15 24 4
gpt4 key购买 nike

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

启动线程后,我调用 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);
}

}

}

我有以下代码

    FirstThread ft = new FirstThread("new thread");
ft.t.join();

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

但它抛出错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type InterruptedException

at ThreadJoin.main(ThreadJoin.java:29)

第 29 行

ft.t.join();

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

最佳答案

Thread#join声明它抛出 InterruptedException。您必须以某种方式处理它 - 要么允许调用者也抛出它,要么捕获它。只需将有问题的行移至 catch block 内即可:

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

关于Java 使用 obj.threadobj.join 抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50772138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com