gpt4 book ai didi

java - 在执行试图中断线程(并失败)并继续执行的 Java 程序后,如何阻止 Ant 挂起?

转载 作者:行者123 更新时间:2023-11-29 06:17:24 25 4
gpt4 key购买 nike

我让 Ant 构建并执行一个 java 程序。这个程序试图做一些有时会挂起的事情,所以我们在一个线程中执行它。

actionThread.start();
try {
actionThread.join(10000);
} catch (InterruptedException e) {
System.out.println("InterruptedException: "+e.getMessage());
}
if (actionThread.isAlive()) {
actionThread.interrupt();
System.out.println("Thread timed out and never died");
}

Ant 调用看起来像这样:

<java fork="true" failonerror="yes" classname="myPackage.myPathName" classpath="build">  
<arg line=""/>
<classpath>
<pathelement location="bin" />
<fileset dir="lib">
<include name="**/*.jar"/>
</fileset>
</classpath>
</java>

当它运行时,我看到“Thread timed out and never died”语句,我还看到主程序完成执行,但 Ant 只是挂起。据推测它正在等待子线程完成,但它们永远不会。

一旦 Ant 执行完 main() 并杀死或忽略死线程,我如何才能完成 Ant?

最佳答案

您可以使用 Thread 类的 public final void setDaemon(boolean on) 方法,即 actionThread.setDaemon(true)。这样,您将确保 JVM 在主线程完成后退出。

Java 文档说:

Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.

This method must be called before the thread is started.

更新


System.exit() 与守护线程

对于较大的代码片段,您不能始终确保所有 Activity 线程都是守护线程。如果守护线程创建了一个新线程,并且它的 setDaemon(true) 没有设置,那么它将从父线程继承。虽然可能会出现将新创建的线程设置为非守护进程的情况(然后我们将面临您当前的问题)。

我个人认为如果你完成了那么你可以调用System.exit(0);

根据 System.exit() 的 Java 文档:

Terminates the currently running Java virtual machine by initiating its shutdown sequence. This method never returns normally...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.

还有其他 SO post 他们讨论过这个:

When should we call System.exit in Java

System.exit() can be used to run shutdown hooks before the program quits. This is a convenient way to handle shutdown in bigger programs, where all parts of the program can't (and shouldn't) be aware of each other.

From which thread should System.exit() be called in a Swing-app?

The GC would take a while before things are rounded off and the app exits. There is nothing wrong with calling System.exit, once you dealt with closing what you ought to.

作为第三种解决方案(第一种是 System.exit() ,第二种是 setDaemon() ),您还可以在进行任何处理之前检查中断的线程,或者在处理 InterruptedException 时决定“做什么”。

希望这会有所帮助。

关于java - 在执行试图中断线程(并失败)并继续执行的 Java 程序后,如何阻止 Ant 挂起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4564607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com