Skip to content

Instantly share code, notes, and snippets.

@claudemartin
Forked from anonymous/SomeClass.java
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save claudemartin/b108b5eaf4d911845f5d to your computer and use it in GitHub Desktop.
Save claudemartin/b108b5eaf4d911845f5d to your computer and use it in GitHub Desktop.
game loop that can bepaused / stopped, now using a Lock.
package com.example.foo;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SomeClass {
public static void main(final String[] args) {
final Thread thread = new Thread(SomeClass::gameLoop);
thread.start();
new Thread(() -> {
try {
Thread.sleep(2000);
} catch (final Exception e) {
e.printStackTrace();
}
lock.lock();
try {
SomeClass.running = false;
SomeClass.isGameRunning.signalAll();
} finally {
lock.unlock();
}
try {
Thread.sleep(2000);
} catch (final Exception e) {
e.printStackTrace();
}
lock.lock();
try {
SomeClass.running = true;
SomeClass.isGameRunning.signalAll();
} finally {
lock.unlock();
}
}).start();
}
static Lock lock = new ReentrantLock();
static Condition isGameRunning = lock.newCondition();
static volatile boolean running = true;
private static void gameLoop() {
try {
if (!running) {
System.out.println("paused!");
lock.lock();
try {
SomeClass.isGameRunning.await();
} finally {
lock.unlock();
}
}
Thread.sleep(500);
} catch (final InterruptedException e) {
return;
}
Thread.yield();
System.out.println("pong");
gameLoop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment