flutter_in_action_2nd icon indicating copy to clipboard operation
flutter_in_action_2nd copied to clipboard

Flutter异常捕获章节关于java线程的说法好像不对

Open songbowen-dev opened this issue 3 years ago • 4 comments

image

songbowen-dev avatar Mar 12 '22 15:03 songbowen-dev

哪里不对

wendux avatar Mar 31 '22 04:03 wendux

单个线程未被捕获的异常不会导致整个进程退出

songbowen-dev avatar Apr 03 '22 13:04 songbowen-dev

+1,我测试了下,jdk8

  1. 非main线程异常未捕获,线程退出,但不会导致进程退出
  2. main线程异常未捕获,
    1. 子线程存在非daemon线程,所有子线程不会退出
    2. 子线程均为daemon线程,所有子线程退出,进程退出

测试代码

public class Test2 {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            while (true) {
                System.out.println("子线程1 " + System.currentTimeMillis());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.setDaemon(true);
        t1.start();

        Thread t2 = new Thread(() -> {
            while (true) {
                System.out.println("子线程2 " + System.currentTimeMillis());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t2.setDaemon(true);
        t2.start();

        System.out.println("主线程1");
        Thread.sleep(5000);
        System.out.println("主线程2");

        // 抛出异常
        produceException();

        System.out.println("主线程3");
        Thread.sleep(10000);
        System.out.println("主线程4");
    }

    public static void produceException() {
        int a = 10 / 0;
    }
}

lewiszlw avatar Sep 27 '22 07:09 lewiszlw

@wendux 官方文档: image https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html

lewiszlw avatar Sep 27 '22 07:09 lewiszlw