Repeatedly Calling System.currentTimeMillis()/nanoTime()
<p>I'm trying create a Thread that keeps track of the time elapsed if a certain event has occurred/is happening. I want to be able to use the elapsed time outside of the thread, like:</p>

<pre><code>if(theChecker.elapsedTime &gt; 5)
    doThis();
</code></pre>

<p>The code that I have basically looks like this:</p>

<pre><code>public class Checker extends Thread {

    public int startTime, elapsedTime;

    @Override
    public void run() {
        while(true) {
            if(check()) {
                if(startTime == 0)
                    startTime = System.currentTimeMillis();
                elapsedTime = System.currentTimeMillis() - startTime;
            }
            else {
                startTime = 0;
                elapsedTime = 0;
            }
        }
     }

     private boolean check() {
         return isSomethingHappening();
     }            

}
</code></pre>

<p>As you can probably guess, this leads to horrendous issues with performance. I've gone as far as making the thread sleep for 250 ms after it calculates the elapsedTime, but performance is still problematic.</p>

<p>Is there a much more performance efficient way to go about this? I'm pretty sure it's something to do with the while loop continuously firing into oblivion, coupled with the fact that System.currentTimeMillis() isn't exactly a free call, memory wise. </p>

<p>Thanks for any replies.</p>
