Discuss / Java / 关于这一节的“多线程”代码

关于这一节的“多线程”代码

Topic source

文中原代码:

public class Main {

    public static void main(String[] args) {

        System.out.println("main start...");

        Thread t = new Thread() {

            public void run() {

                System.out.println("thread run...");

                try {

                    Thread.sleep(10);

                } catch (InterruptedException e) {}

                System.out.println("thread end.");

            }

        };

        t.start();

        try {

            Thread.sleep(20);

        } catch (InterruptedException e) {}

        System.out.println("main end...");

    }

}

然后我修改成

public class Main {

    public static void main(String[] args) {

        System.out.println("main start...");

        Thread t = new Thread() {

            public void run() {

                System.out.println("thread run...");

                try {

                    Thread.sleep(10);

                } catch (InterruptedException e) {}

                System.out.println("thread end.");

            }

        };

        t.start();

        t.join();  //添加了这个代码后为什么会报错unreported exception InterruptedException; must be caught or declared to be thrown

        try {

            Thread.sleep(20);

        } catch (InterruptedException e) {}

        System.out.println("main end...");

    }

}

join()、sleep() 方法都可能会抛出 InterruptedException 异常,需要使用 try 捕捉异常

try {
    t.join();
    Thread.sleep(20);
} catch (InterruptedException e) {}

这样可以正常运行。


  • 1

Reply