multithreading - Java Multi-Thread Pausing -
my goal
i brand new multi-threading in java , attempting create pong. include bit of code here relevant question.
problem
i want able pause game pressing space bar, , resume again pressing space bar later. following code works pause game, cannot resume. future key presses not recognized. seems if main thread being paused.
code
main class
public class mainmanager { private ticker ticker; private thread tickerthread; private boolean active; public mainmanager() { ticker = new ticker(this,10); tickerthread = new thread(ticker); tickerthread.start(); } public synchronized void tick() { // necesary things each game tick } public void togglestate() { if (this.active) { ticker.pause(); } else { this.setactive(true); notify(); } } public void setactive(boolean b) { this.active = b; } public static void main(string[] args) { swingutilities.invokelater(new runnable() { @override public void run() { mainmanager manager = new mainmanager(); } }); } }
ticker class
public class ticker implements runnable { private mainmanager manager; private int tick; public ticker(mainmanager manager,int tick) { this.manager = manager; this.tick = tick; } @override public void run() { manager.setactive(true); while (true) { try { thread.sleep(this.tick); } catch (interruptedexception e) { e.printstacktrace(); } manager.tick(); } } public void settickspeed(int speed) { this.tick = speed; } public synchronized void pause() { synchronized(manager) { try { system.out.println("waiting manager"); manager.setactive(false); manager.wait(); } catch (interruptedexception e) { e.printstacktrace(); } } } }
keylistener class
note: this class added jframe constructed inside of mainmanager constructor. if jframe class important question post code, let me know
public class keyboardlistener implements keylistener { private mainmanager manager; public keyboardlistener(mainmanager manager) { this.manager = manager; } @override public void keypressed(keyevent e) { system.out.println("keypressed); //this line prints on first spacebar. //after game paused, never prints again. despite me spamming spacebar if (e.getkeycode() == keyevent.vk_space) { manager.togglestate(); } } }
how tickerthread
pause , resume press of key? other criticisms welcome.
you never left swing event dispatch thread.
your ticker merrily ticking away in other thread, working fine. however, if follow path of toggle call, never reaches other thread.
your space key pressed->swing edt witchcraft->keypressed->manager.togglestate()->ticker.pause() synchronize manager, isn't hard. we're still on main thread! wait.
your space key pressed->swing edt paused. part of ticker that's running in thread run method.
you want run relating game logic off edt. run both mainmanager , ticker in different thread jframe , event handlers , synchronize or use locked boolean value send data io thread logic thread.
Comments
Post a Comment