首页 > 试题广场 >

以下代码运行后会打印哪些内容 public class&nb

[单选题]
以下代码运行后会打印哪些内容
public class Test implements Runnable {
    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            synchronized (this) {
            try {
                wait();
            } catch (InterruptedException e) {
                System.out.println("InterruptedException");
            }
        }
    }
    System.out.println("Final");
}
public static void main(String[] args) throws InterruptedException {
    Thread thread = new Thread(new Test());
    thread.start();
    new Thread(() -> {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        thread.interrupt();
        System.out.println("interrupt");
    }).start();
    thread.join();
    System.out.println("exit");
    }
}

  • interrupt、InterruptedException
  • exit、interrupt、InterruptedException
  • exit、interrupt、InterruptedException、final
  • interrupt、InterruptedException、final
捕获到异常后,中断标志位会被重置为false,所以不会退出循环,楼上几个在说些什么东西啊???
发表于 2023-03-18 16:22:19 回复(0)
首先有三个线程,main线程,无名线程,以及thread,无名线程和thread肯定是thread运行时间更长,因为是一个无限循环,并且无名线程会去结束thread.运行逻辑是,主线程(父线程)运行到了join( )方法后,停在原地,等thread线程(子线程)执行完毕。
综上,线程结束的时间:new的无名线程  --早于-- thread--早于--主线程,那么可以排出BC,exit肯定是最后输出的。
对于A,斗胆猜测是因为抛出异常发生thread线程,涉及到一个线程和另外一个线程通信,估计还是本线程的输出更快,所以先输出本线程(new Thread)的interrupt,然后被中断线程抛出异常并处理。

对于interrupt(),是终止“阻塞状态”而不是终止掉线程。

抛出异常后,thread线程的while并不会终止运行,所以final也不会输出。参考:(7条消息) Java多线程 interrupt中断阻塞_一只老风铃的博客-CSDN博客_interrupt中断线程的阻塞状态,D排除,选择A。


发表于 2022-05-10 19:55:52 回复(0)
wait()时,若是线程被中断了,那么这种情况下,该线程会将中断标记清除,同时抛出中断异常。
故while中判断是否中断的取反,永远都是true
发表于 2024-08-05 12:16:09 回复(0)

thread.interrupt(), 线程自己决定合适抛出InterruptException

阻塞状态:直接抛出异常

运行状态:修改标志位,抛出异常

thread线程,wait()而进入阻塞,被匿名线程interrupt()thread直接抛出异常,没有修改标志位,因此不会退出while循环,最终导致不会打印exit

发表于 2023-03-20 21:17:21 回复(0)
interrupt()使thread直接进入异常,而且interrupt标志位置为false。
发表于 2021-09-01 09:06:24 回复(0)