Created
December 28, 2012 02:03
-
-
Save mdellavo/4393857 to your computer and use it in GitHub Desktop.
Pausable Thread Class
This file contains hidden or 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
class PausableThread extends Thread { | |
private boolean running, paused; | |
private static final int FPS = 30; | |
public PausableThread() { | |
super(); | |
pauseRunning(); | |
} | |
@Override | |
public void start() { | |
super.start(); | |
startRunning(); | |
} | |
public synchronized void startRunning() { | |
running = true; | |
} | |
public synchronized boolean isRunning() { | |
return running; | |
} | |
public synchronized void stopRunning() { | |
running = false; | |
} | |
public synchronized void pauseRunning() { | |
paused = true; | |
notifyAll(); | |
} | |
public synchronized void resumeRunning() { | |
paused = false; | |
notifyAll(); | |
} | |
public synchronized void waitForResume() { | |
while(paused) { | |
try { | |
wait(); | |
} catch(InterruptedException e) { | |
} | |
} | |
} | |
public void throttle(int timeslice, long elapsed) { | |
if(elapsed < timeslice) { | |
try { | |
Thread.sleep(timeslice - elapsed); | |
} catch(InterruptedException e) { | |
} | |
} | |
} | |
public void update(long elapsed) { | |
} | |
@Override | |
public void run() { | |
int frames = 0; | |
long last = System.currentTimeMillis(); | |
while (isRunning()) { | |
frames++; | |
waitForResume(); | |
long now = System.currentTimeMillis(); | |
long elapsed = now - last; | |
update(elapsed); | |
now = System.currentTimeMillis(); | |
elapsed = now - last; | |
last = now; | |
throttle(1000/FPS, elapsed); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment