Skip to content

Instantly share code, notes, and snippets.

@ra1u
Created May 27, 2015 20:12
Show Gist options
  • Save ra1u/52dbe69b95d412cfab8e to your computer and use it in GitHub Desktop.
Save ra1u/52dbe69b95d412cfab8e to your computer and use it in GitHub Desktop.
thread safe loop performance test
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