【问题标题】:Java using obj.threadobj.join throws errorJava 使用 obj.threadobj.join 抛出错误
【发布时间】:2018-11-19 04:38:32
【问题描述】:

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

启动线程后,我调用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 创建一个新线程并使其首先完成。

但它会抛出错误:

线程“main”java.lang.Error 中的异常:未解决的编译 问题:未处理的异常类型InterruptedException

在 ThreadJoin.main(ThreadJoin.java:29)

第 29 行

ft.t.join();

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

【问题讨论】:

  • 在尝试执行程序之前是否考虑过修复编译错误?
  • 我知道为什么这个问题值得一票否决

标签: java multithreading exception compiler-errors


【解决方案1】:

Thread#join 声明它抛出一个InterruptedException。您必须以某种方式处理它 - 要么允许调用者也抛出它,要么抓住它。只需将违规行移到 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);
}

【讨论】:

  • 非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-14
  • 2014-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多