Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Threads -- Waiting for events  RSS feed

 
Ray Muirhead
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there

Got a slight problem (maybe) here with threads and waiting for action from a player in a game. The play() method keeps cycling through the NPCs, checking if each is faster than the player. If the player has not acted yet that round and is faster, the waitForPlayer() method is called until the player has acted (another method changes playerDone to true). What I am curious about is whether there is a way to make the main() thread just sit there and wait for an event to come in signalling that the player has acted, the same way the Swing event dispatch thread works? That way waitForPlayer() could just chill out instead of running through a while loop until the boolean is changed, and return when an event has come in signalling the players action. There seem to be some serious holes in my logic here, but I'm working on this myself so I don't have anyone to bounce ideas off. Kind of stuck in a vacuum.



Muchas gracias!

[ September 17, 2004: Message edited by: Ray Muirhead ]
[ September 17, 2004: Message edited by: Ray Muirhead ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a nutshell, the main loop can call Object.wait() on some object, and the player can call notify() on that same object. wait() sleeps forever or until some other thread calls notify() on that object. This is exactly what you're looking for.

You could read Sun's tutorial on threading, especially this part, to learn about this; c'mon back with questions.
 
Ray Muirhead
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Ernest, I thought there would be something in the API, but I just couldn't find it, and it wasn't in Head First Java.

Cheers!
 
Ray Muirhead
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Feeling a little humbled -- this threads stuff is hard! Got it working ok, but still figuring out how to synch it up tight so that the player can only act once and only act in her turn.

Thanks for the pointer Earnest.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!