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

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

我也想知道在此特定示例中try块的目的是什么.我了解try块通常会做什么,但是具体来说try块对线程有什么作用.

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!");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值