-
-
Save claudemartin/b108b5eaf4d911845f5d to your computer and use it in GitHub Desktop.
game loop that can bepaused / stopped, now using a Lock.
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
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