Discuss / Java / 不确定这样理解有没问题,打笔记前的一个草稿

不确定这样理解有没问题,打笔记前的一个草稿

Topic source

对老师的代码进行改写

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new MyThread();
        t.start();
        Thread.sleep(1000);  //保证子线程有足够时间执行
        t.interrupt(); // 中断t线程
        t.join(); // 等待t线程结束
        System.out.println("end");
    }
}

class MyThread extends Thread {
    public void run() {
        Thread hello = new HelloThread();
        hello.start(); // 启动hello线程
        System.out.println("a");
        try {
            hello.join(); // 等待hello线程结束
        } catch (InterruptedException e) {
            System.out.println("interrupted!");
        }
        hello.interrupt();
        System.out.println("c");
    }
}

class HelloThread extends Thread {
    public void run() {
        int n = 0;
        while (true) {
            n++;
            System.out.println(n + " hello!");
            try {
                Thread.sleep(500);
                System.out.println("b");  
            } catch (InterruptedException e) {
                System.out.println("d");
                break;
            }
        }
    }
}

输出结果

a
1 hello!
b
2 hello!
interrupted!
c
d
end

猜想1:线程在执行到 HelloThread->Thread.sleep(500); 的时候会并发执行 MyThread->hello.interrupt(); 方法。

猜想2:如果 Main->Thread.sleep(1000);休眠的时间不够或被注释,那么HelloThread->Thread.sleep(500);之后的函数都不会被执行到,因为线程并发执行了 MyThread->hello.interrupt(); 触发了catch语句。

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new MyThread();
        t.start();
        Thread.sleep(999);  //保证子线程有足够时间执行
        t.interrupt(); // 中断t线程
        t.join(); // 等待t线程结束
        System.out.println("end");
    }
}

class MyThread extends Thread {
    public void run() {
        Thread hello = new HelloThread();
        hello.start(); // 启动hello线程
        System.out.println("a");
        try {
            hello.join(); // 等待hello线程结束
        } catch (InterruptedException e) {
            System.out.println("interrupted!");
        }
        hello.interrupt();
        System.out.println("c");
        System.out.println("x");
        System.out.println("z");
        System.out.println("m");
        System.out.println("n");
    }
}

class HelloThread extends Thread {
    public void run() {
        int n = 0;
        while (true) {
            n++;
            System.out.println(n + " hello!");
            try {
                Thread.sleep(1000);
                //如果 main 的Thread.sleep(1000);被注释或者休眠时间不够,那么以下所有函数都不会被执行到
                System.out.println("b");  
            } catch (InterruptedException e) {
                System.out.println("d");
                break;
            }
        }
    }
}

输出结果

a
1 hello!
interrupted!
c
x
z
d
m
n
end

  • 1

Reply