gpt4 book ai didi

java - 如何在 Java 中获取线程信息/统计信息

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:19:51 26 4
gpt4 key购买 nike

标题说明了一切。我有一些代码包含在下面,我想知道如何获取与线程相关的统计信息/信息(即有多少不同的线程正在运行,不同线程的名称)。为了保持一致性,想象代码是使用 22 33 44 55 作为命令行参数运行的。

我还想知道 try block 在这个特定示例中的用途是什么。我了解 try block 的一般作用,但特别了解 try block 对线程的作用。

public class SimpleThreads {
//Display a message, preceded by the name of the current thread
static void threadMessage(String message) {
long threadName = Thread.currentThread().getId();
System.out.format("id is %d: %s%n", threadName, message);
}
private static class MessageLoop implements Runnable {
String info[];
MessageLoop(String x[]) {
info = x;
}
public void run() {
try {
for (int i = 1; i < info.length; i++) {
//Pause for 4 seconds
Thread.sleep(4000);
//Print a message
threadMessage(info[i]);
}
} catch (InterruptedException e) {
threadMessage("I wasn't done!");
}
}
}

public static void main(String args[])throws InterruptedException {
//Delay, in milliseconds before we interrupt MessageLoop
//thread (default one minute).
long extent = 1000 * 60;//one minute
String[] nargs = {"33","ONE", "TWO"};
if (args.length != 0) nargs = args;
else System.out.println("assumed: java SimpleThreads 33 ONE TWO");
try {
extent = Long.parseLong(nargs[0]) * 1000;
} catch (NumberFormatException e) {
System.err.println("First Argument must be an integer.");
System.exit(1);
}
threadMessage("Starting MessageLoop thread");
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop(nargs));
t.start();

threadMessage("Waiting for MessageLoop thread to finish");
//loop until MessageLoop thread exits
int seconds = 0;
while (t.isAlive()) {
threadMessage("Seconds: " + seconds++);
//Wait maximum of 1 second for MessageLoop thread to
//finish.
t.join(1000);
if (((System.currentTimeMillis() - startTime) > extent) &&
t.isAlive()) {
threadMessage("Tired of waiting!");
t.interrupt();
//Shouldn't be long now -- wait indefinitely
t.join();
}

}
threadMessage("All done!");
}
}

最佳答案

你可以使用VisualVM用于线程监控。它包含在 JDK 6 update 7 及更高版本中。您可以在 JDK 路径/bin 文件夹中找到 visualVm。

VisualVM presents data for local and remote applications in a tab specific for that application. Application tabs are displayed in the main window to the right of the Applications window. You can have multiple application tabs open at one time. Each application tab contains sub-tabs that display different types of information about the application.VisualVM displays real-time, high-level data on thread activity in the Threads tab.

enter image description here

关于java - 如何在 Java 中获取线程信息/统计信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13895605/

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