gpt4 book ai didi

Java 主类线程不再使用 Java 多线程终止

转载 作者:行者123 更新时间:2023-11-29 04:18:03 24 4
gpt4 key购买 nike

我创建了自己的线程类来实现 Runnable 接口(interface)。但是每次我开始将自己的线程类作为新线程运行时,主类线程不再自行终止。这只是 Eclipse 中的一个问题,还是我在服务器上运行它时也会遇到问题?我是否必须更改调用线程的内容以便 main 方法可以正确终止?


这是我的基本自制线程:

public class OwnThread implements Runnable {
@Override
public void run() {
//do something
}
}

这是不再终止的主类:

public static void main(String[] args) {    
Thread thread = new Thread(new OwnThread());
thread.start();
}

当我调试它时,最后调用的方法是 Thread 类的 exit() 方法。完成这些代码行后,该过程将永远持续下去:

/**
* This method is called by the system to give a Thread
* a chance to clean up before it actually exits.
*/
private void exit() {
if (group != null) {
group.threadTerminated(this);
group = null;
}
/* Aggressively null out all reference fields: see bug 4006245 */
target = null;
/* Speed the release of some of these resources */
threadLocals = null;
inheritableThreadLocals = null;
inheritedAccessControlContext = null;
blocker = null;
uncaughtExceptionHandler = null;
}

这是永远运行的线程的屏幕截图。 TestInterface 类是 main 方法所在的位置:

Thread running on forever

最佳答案

But every time I start running my own thread class as a new thread, the main class thread does not terminate anymore by itself.

这有点不对。您的程序不会终止,因为至少存在一个仍在运行的非守护线程。规则是:如果所有非守护线程都终止,则 Java 程序终止。

我修改了您的程序以明确此行为:

public class OwnThread implements Runnable {
@Override
public void run() {
runForever();
}

public static void main(String[] args) {
Thread thread = new Thread(new OwnThread());
thread.start();
runForever();
}

private static void runForever() {
while (true) {}
}
}

运行将创建两个将永远运行的线程。一个是运行程序启动的主线程,一个是main方法内部启动的线程:

enter image description here

通过删除 main 方法中对 runForever 的调用来修改上述代码 ...

public static void main(String[] args) {
Thread thread = new Thread(new OwnThread());
thread.start();
}

...将导致不同的线程图片:

enter image description here

这里主线程没有了,因为它被终止了。但是另一个启动的线程仍在运行。

旁注:突然出现另一个线程 - DestroyJavaVM。看看帖子DestroyJavaVM thread ALWAYS running获取更多信息。

关于Java 主类线程不再使用 Java 多线程终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51055780/

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