【问题标题】:What are the background threads in active thread count in java?java中活动线程数中的后台线程是什么?
【发布时间】:2018-05-09 10:36:28
【问题描述】:

我正在使用具有 10 个固定线程的 ExecutorService。

  ExecutorService service = Executors.newFixedThreadPool(10);

当我试图找出线程数时使用

  System.out.println(Thread.activeCount());

输出从 11 变化到 15。

我知道其中一个线程是主线程。

但是其他线程是什么?

【问题讨论】:

  • 垃圾收集器可能使用线程。根据您使用的库/框架,它们也可能使用线程,但您没有对此指定任何内容。

标签: java multithreading executorservice


【解决方案1】:

Java 中有少数线程在后台运行,例如用于调用 finalize() 方法的终结器。您可以通过查看最父ThreadGroup来打印它们:

ThreadGroup group = Thread.currentThread().getThreadGroup();
while (group.getParent() != null) {
  group = group.getParent();
}
Thread[] threads = new Thread[group.activeCount()];
group.enumerate(threads);
Arrays.stream(threads).forEach(System.out::println);

它会输出类似

的东西
Thread[Reference Handler,10,system]
Thread[Finalizer,8,system]
Thread[Signal Dispatcher,9,system]
Thread[Attach Listener,5,system]
Thread[main,5,main]
Thread[Monitor Ctrl-Break,5,main]

在您的示例中,Thread.activeCount()Thread.currentThread().getThreadGroup().activeCount() 的简写,因此您正在查看最顶层的当前线程组。

【讨论】:

    猜你喜欢
    • 2011-01-15
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 2011-07-11
    • 2010-11-22
    • 1970-01-01
    • 2020-10-15
    • 2019-12-02
    相关资源
    最近更新 更多