有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (3) 个答案

  1. # 1 楼答案

    在多线程应用程序中,有多个线程正在执行Thread.currentThread().interrupt()只会中断当前正在执行的线程,但剩余的线程仍将运行,即使主线程被中断

    然而,System.exit(0)会导致系统终止。。所有的线程都被杀死了

  2. # 2 楼答案

    如果有其他(非守护进程)线程在运行,那么如果停止主线程,JVM将不会退出。系统exit()终止所有其他线程

  3. # 3 楼答案

    总结

    1. thread.interrupt()不会停止线程。它用于多线程程序中的协调。除非你确切知道自己在做什么,否则不要使用它
    2. 抛出RuntimeException将(通常)终止线程,但不一定终止程序
    3. System.exit(int)几乎总是终止程序并返回状态码
    4. 在异常情况下,System.exit(int)可能不会真正停止程序Runtime.getRuntime().halt(int)另一方面,总是这样

    线程中断

    恐怕你的第一句话错了Thread.currentThread().interrupt()不会停止线程或程序

    中断线程是一种表示它应该停止的方式,但这是一种合作的努力:线程中的代码应该不时检查中断的状态,并且(在大多数情况下——但即使这只是可选的)如果被中断,也应该停止。如果不这样做,什么也不会发生

    具体来说,中断一个线程(任何线程,包括当前正在执行的线程)只会设置中断标志。标准库中的某些方法将抛出InterruptedException,但这也只是一种表示线程已被中断的方式。在这种情况下应该做什么取决于该线程中运行的代码

    以下是Brian Goetz的《Java并发实践》一书中的相关部分:

    Thread provides the interrupt method for interrupting a thread and for querying whether a thread has been interrupted. Each thread has a boolean property that represents its interrupted status; interrupting a thread sets this status.

    Interruption is a cooperative mechanism. One thread cannot force another to stop what it is doing and do something else; when thread A interrupts thread B, A is merely requesting that B stop what it is doing when it gets to a convenient stopping point if it feels like it.While there is nothing in the API or language specification that demands any specific application level semantics for interruption, the most sensible use for interruption is to cancel an activity. Blocking methods that are responsive to interruption make it easier to cancel long running activities on a timely basis.

    例外和系统。出口(内部)

    报告说:

    Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

    所以调用exit()肯定会(几乎)停止你的程序。与抛出RuntimeException(或Error)不同,这不能在调用堆栈的某个地方被捕获,也不取决于是否有其他线程在运行。另一方面,未捕获的异常会终止抛出它的线程,但如果存在任何其他(非守护进程)线程,程序将继续运行

    抛出异常的另一个区别是exit()不会向控制台打印任何内容(与未捕获的异常一样),而是让程序返回特定的状态代码。状态代码有时用于shell或批处理脚本,但除此之外,它们不是很有用

    运行时。暂停(int)

    最后(为了完整起见),我想指出退出Java程序的第三种可能性。当调用System.exit(int)时(或者程序以其他方式结束),运行时会在Java虚拟机停止之前进行一些清理工作。这在Runtime.exit(int)的Javadoc中有描述(被System.exit(int)称为:

    The virtual machine's shutdown sequence consists of two phases. In the first phase all registered shutdown hooks, if any, are started in some unspecified order and allowed to run concurrently until they finish. In the second phase all uninvoked finalizers are run if finalization-on-exit has been enabled. Once this is done the virtual machine halts.

    如果任何关闭钩子或终结器被阻止完成,例如因为deadlock,程序可能永远不会真正退出。保证JVM停止的唯一方法是Runtime.halt(int)

    This method should be used with extreme caution. Unlike the exit method, this method does not cause shutdown hooks to be started and does not run uninvoked finalizers if finalization-on-exit has been enabled.