java多线程和cpu,Java中线程用户时间和线程cpu时间的区别

The ThreadMXBean has two methods for retrieving thread time usage:

What is the difference between the two?

Update 2: If I'm able to link to the javadocs, please don't quote them - I've read them already.

Update: here's some code which I tried to use to learn what these times mean, with little success:

ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

threadMXBean.setThreadContentionMonitoringEnabled(true);

long mainThreadId = getMainThreadId(threadMXBean);

logTimes("Start", threadMXBean, mainThreadId);

URL url = new URL("https://hudson.dev.java.net");

URLConnection connection = url.openConnection();

connection.getContent();

logTimes("After loading", threadMXBean, mainThreadId);

and the output is:

Start Tue Jun 16 16:13:40 EEST 2009 Cpu time : 80, user time: 60, waited: 0, blocked: 0

After loading Tue Jun 16 16:13:43 EEST 2009 Cpu time : 1,020, user time: 960, waited: 0, blocked: 0

So the difference between cpu and user time increased from 20 to 60 milliseconds. Is that because using a HttpUrlConnection does include some network I/O?

解决方案

As the API docs you linked to yourself already point out

getThreadCpuTime

If the implementation distinguishes

between user mode time and system mode

time, the returned CPU time is the

amount of time that the thread has

executed in user mode or system mode.

If the implementation of the JVM distinguishes between user mode and kernel mode time there could be a difference in the results of the two functions.

Further the value is only precise to the nanosecond and the value has an overflow problem if the offset is > 2^63. The JVM must also support measuring the CPU time for the current thread and it must be enabled.

On Win32 the return values should be the same as the ones you get from the GetThreadTimes Function

getThreadUserTime() -> lpUserTime * 100 //or something like this

getThreadCpuTime() -> (lpKernelTime + lpUserTime) * 100 //or something like this

And a more clear reference to User Mode vs Kernel Mode

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值