multithreading - Java thread switching -


i have program supposed run multiple threads @ same time.

it's simulation of card game uno, , you're supposed have thread each player.

now here's catch: whenever player has card same number , color of card on top of dump in hand it's not player's turn, can 'cut' line , put card down. player next player cut line continues.

i have class player :

class player implements runnable {      public boolean ishisturn = false;      public thread makemove(final card topcard, final boolean ishisturn) {         thread thread = new thread(this);         thread.start();         return thread;     } } 

thread.start() starts run method, have logic , decision making. @ beggining of run() thread sleeps random of 300 - 700 miliseconds, make cutting line possible in time frame.

my question is, should store threads somewhere, , if so, where, , how can switch between threads when it's different player's turn? know has boolean ishisturn, don't know how use it.

and yes, homework, i'm asking small piece of it, don't want complete answer, push me in right direction.

and how can switch between threads when it's different player's turn?

the distinguishing feature of threads several threads can run @ same time. if don't use feature, there no point in using threads. since player can move when isn't turn, makes sense players active @ same time. therefore, i'd create (and start) single thread per player. thread alternate between sleeping , moving.

that leaves question of how threads can interact. that, i'd create class like:

class game {     card topcard;     player nextplayer;      ... } 

and give instance of game each player thread. when playing thread thinking move, can @ top card, , whether turn. when making move, updates fields in game instance.

of course, since different threads can active @ same time, possible 2 players try move @ same time (or put differently, player may decide play card, player faster, making initial player's move no longer valid). easiest prevented synchronizing access game instance. realism, might tempted synchronize when looking @ game state, think, , synchronize again make move. however, might easier synchronize on entire "look, think , move" cycle, because ensures players don't interfere each others thinking, , reduces number of corner cases need handle.

another wrinkle termination. game ends first player has no cards left, other players need way notice fact. easiest finishing player declare himself winner (for instance, setting field winningplayer in game instance) , other threads terminate winner declared.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -