Mike, It depends on what you mean by "how long a thread has run totally"... if you mean how long a thread has been "alive" (i.e. started running to ended running), it is pretty easy... just save System.currentTimeMillis() at the start of the run method, then take the difference between the saved value and System.currentTimeMillis() again at the end of the run method. If you instead mean the time the thread has been in the "Runnable" state... well, it is just about impossible to get an accurate measurement of that... you could get a value that (might) be kinda close by making a loop that saves System.currentTimeMillis() at the start of the loop, then takes the difference between the saved value and System.currentTimeMillis() at the end of the loop and keeps adding this value to a variable keeping track of total time... but this does not take into account a thread being "interrupted" in the middle of its run method to let another thread run, so it will not be accurate... HTH, -Nate
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
Joined: Mar 11, 2001
Hi Nathan, Thank you very much for your reply. What I want to do is the first case you mentioned. I am doing an exercise, with two threads of different priority. While two threads running, I want to show how much time each thread has run. That's a better way to track the system time at the beginning and end of the run() method. Is there such a possibility that the thread was interrupted by scheduler in the middle of run()? Mike
Absolutely. Which is why I suspect that what you really want is the second case, not the first. You might start 100 threads at once (or as close to simultaneously as possible) and let them all run for ten minutes. Each one would show as having been alive for ten minutes - but they weren't all running in the processor simultaneously, and there's no easy way to tell how much time each thread spent in the processor. You can get some idea of this by having each thread print something periodically to standard output which identifies the thread and says something about how much progress it has made. That doesn't translate directly into time units, but it gives you some idea at least.
"I'm not back." - Bill Harding, Twister
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: How to keep track of running time of a thread