1
new Thread(new Runnable() {
   @Override public void run() {
    //calculations #1
    }
 }).start();
new Thread(new Runnable() {
   @Override public void run() {
    //calculations #2
    }
}).start();

1) I want to measure the execution time of any thread and then sum into a total-time variable. Can anyone explain me how?

2) If thread has only a cycle inside (for, while) and the cycle ends, also ends the thread?

Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
Northumber
  • 315
  • 2
  • 3
  • 15
  • check this http://stackoverflow.com/questions/180158/how-do-i-time-a-methods-execution-in-java – Sony Jul 11 '15 at 16:45
  • 4
    You could write your own `TimedThread extends Thread`. By overwriting the `start()` method, you can take the time before and after executing the `Runnable` and store the consumed time within a field of `TimedThread`. As to the second question: The thread ends, yes (`isAlive()` will return `false`), but if you stored the Object, it will be accessible (i.e. you could access the `consumedTime` of `TimedThread`). – Turing85 Jul 11 '15 at 16:46
  • but `start()` is not a blocking method, so it will return immediately. – felipe_gdr Dec 17 '20 at 05:26

1 Answers1

0

You basically need a resource that you can access and mutate form multiple threads. An atomic integer could be helpful in your case. See this discussion - Practical uses for AtomicInteger.

To answer your second question - I am assuming your run method has a single while loop and when the loop is exited the control exists even out our run. So yes, when the run exits the thread has completed its work. If you are interested in a more detailed discussion on the lifecycle of a thread check out this post - How to start/stop/restart a thread in Java?.

Community
  • 1
  • 1
Y123
  • 915
  • 13
  • 30