所以在下面:
public class JavaClass {
public static void main(String[] args) {
JavaClass clazz = new JavaClass();
clazz.startCustomThread();
clazz = new JavaClass();
clazz.startCustomThread();
}
public void startCustomThread() {
new MyThread().startThread();
}
private static class MyThread {
public void startThread() {
new Thread(() -> {
System.out.println("In thread " + Thread.currentThread().getName());
while (true) {
try {
Thread.sleep(1000 * 5);
System.out.println("Woke up " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
}
输出是:
In thread Thread-1
In thread Thread-0
Woke up Thread-0
Woke up Thread-1
....
因为 clazz
应该在第二个实例之后进行 GC,并且第一个线程在第一次调用 startCustomThread()
的本地范围内启动
我的问题是为什么第一个线程没有终止?
最佳答案
您调用了 startCustomThread
方法两次,因此您启动了 2 个线程。
来自 Thread
文档:
The Java Virtual Machine continues to execute threads until either of the following occurs:
- The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
- All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
这些选项均不适用于您的情况,因此线程仍然存在。这与垃圾收集无关。
关于java - 为什么有两个运行线程而不是一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57543974/