在IntelliJ上调试或运行时,线程数不同

时间:2015-05-31 18:59:04

标签: multithreading intellij-idea

我使用以下代码: -

public static void main(String[] args) {
        int threadPool = 4;
        System.out.println("initial count---" + Thread.activeCount());
        Thread.currentThread();
}

输出不同 在IntelliJ上调试时: - initial count---1

在IntelliJ上运行时: - initial count---2

当我运行这个程序时,我无法理解什么是额外的线程。

1 个答案:

答案 0 :(得分:3)

IntelliJ在运行时有一个额外的线程:

"Monitor Ctrl-Break" 
       java.lang.Thread.State: RUNNABLE
            at java.net.DualStackPlainSocketImpl.accept0(Native Method)
            at java.net.DualStackPlainSocketImpl.socketAccept(DualStackPlainSocketImpl.java:131)
            at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:398)
            at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:199)
            at java.net.ServerSocket.implAccept(ServerSocket.java:530)
            at java.net.ServerSocket.accept(ServerSocket.java:498)
            at com.intellij.rt.execution.application.AppMain$1.run(AppMain.java:90)
            at java.lang.Thread.run(Thread.java:745)

您可以使用以下方式打印它们:

/** from http://crunchify.com/how-to-generate-java-thread-dump-programmatically/ */
public static String crunchifyGenerateThreadDump() {
    final StringBuilder dump = new StringBuilder();
    final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    final ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100);
    for (ThreadInfo threadInfo : threadInfos) {
        dump.append('"');
        dump.append(threadInfo.getThreadName());
        dump.append("\" ");
        final Thread.State state = threadInfo.getThreadState();
        dump.append("\n   java.lang.Thread.State: ");
        dump.append(state);
        final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace();
        for (final StackTraceElement stackTraceElement : stackTraceElements) {
            dump.append("\n        at ");
            dump.append(stackTraceElement);
        }
        dump.append("\n\n");
    }
    return dump.toString();
}