gpt4 book ai didi

java - 为什么我的代码中第一个 Thread.activeCount() 返回 1 而另一个返回 2?

转载 作者:行者123 更新时间:2023-12-01 13:07:46 25 4
gpt4 key购买 nike

这是我的申请:

public class NamedThread extends Thread {
/* This will store name of the thread */

String name;

@Override
public void run() {
//Will store the number of threads
int count = 0;
while (count <= 3) {
//Display the number of threads
System.out.println(Thread.activeCount());
//Display the name of the currently running thread
name = Thread.currentThread().getName();
count++;
System.out.println(name);
if (name.equals("Thread1")) {
System.out.println("Marimba");
} else {
System.out.println("Jini");
}
}
}

public static void main(String args[]) {
NamedThread objNamedThread = new NamedThread();
objNamedThread.setName("Thread1");
//Display the status of the thread, whether alive or not
System.out.println(Thread.currentThread().isAlive());
System.out.println(objNamedThread.isAlive());
/*invokes the start method which in turn will call
* run and begin thread execution
*/
objNamedThread.start();
System.out.println(Thread.currentThread().isAlive());
System.out.println(objNamedThread.isAlive());
}
}

输出是:

true
false
true
true
1
Thread1
Marimba
2
Thread1
Marimba
2
Thread1
Marimba
2
Thread1
Marimba

我的申请有什么问题,为什么?谢谢!

最佳答案

public static void main(String[] args) {
System.out.println(Thread.activeCount());

//doSomething()
}

上面的代码输出2

GC占用一个线程,所以你得到2个,而不是1

该函数是为调试而设计的

如果你在 Debug模式下运行,你会得到 1

关于java - 为什么我的代码中第一个 Thread.activeCount() 返回 1 而另一个返回 2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23140478/

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