Created
May 27, 2015 20:12
-
-
Save ra1u/52dbe69b95d412cfab8e to your computer and use it in GitHub Desktop.
thread safe loop performance test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.Runnable; | |
import java.lang.Thread; | |
import java.lang.InterruptedException; | |
import java.util.concurrent.atomic.AtomicLong; | |
class timeThread { | |
private | |
static AtomicLong running_ms = | |
new AtomicLong(0); // atomic is thread safe variable | |
private | |
static long start = System.currentTimeMillis(); | |
public | |
static void main(String[] args) { | |
Thread incrementTimer = new Thread(runClock); | |
incrementTimer.start(); | |
long counter = 0; | |
long timeout = 1000; | |
while (true) { | |
long time = running_ms.get(); | |
if (time <= timeout) { | |
++counter; | |
} else { | |
System.out.print(counter / time + "\r"); | |
timeout = time + 1000; | |
}; | |
} | |
}; | |
static Runnable runClock = new Runnable() { | |
public | |
void run() { | |
while (true) { | |
long now = System.currentTimeMillis(); | |
running_ms.set(now - start); | |
try { | |
Thread.sleep(1); | |
} catch (InterruptedException ie) { | |
}; | |
} | |
}; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment