java - 为什么有两个运行线程而不是一个?

标签 java multithreading concurrency scope garbage-collection

所以在下面:

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:

  1. The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
  2. 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/

相关文章:

java - 从 Java 调用 curl 命令

java - 在使用 googleapp 引擎时使用 apache commons 库

java - Java中根据子类Type定义父类方法的泛型Type

java - 从命令行调用时使用处理 opengl 库缺少什么?

ios - iOS performSelectorInBackground内部的performSelectorInBackground

java - 确保所有等待线程完成

c - 如果在运行时之前不知道它们的数量,如何使用 POSIX C 线程?

java - 除了 AsyncTask 之外,Android 中是否还有可以从另一个线程在 UI 线程上执行某些操作的方法?

c# - 等待所有线程完成写入 ConcurrentDictionary

c - fork() 和 pipeline() 的竞争条件