0

I am currently working on a mutltithreading game which uses threads as players and can create n players, so synchronization has to be really good. My players do functions while sum of their hand isn't equal to 100. If it is thread changes variable game on to false and therefore stop the game.

public void run(){                                                                         
while(gameOn) {                                                                        
    takeHand();                                                                        
    while (sum() != 100 && !isInterrupted()) {                                         
        discardPebble();                                                               
        drawnPebble();                                                                 
        System.out.println(sum() + " "+ hand.toString() + currentThread().getName());  
        try {                                                                          
            Thread.sleep(100);                                                         
        } catch (InterruptedException b) {                                             
            System.out.println("We have a winner!");                                   

        }                                                                              
    }                                                                                  
    StopGame();                                                                        
}                                                                                      
b.close(); // closing output stream to the file

As you can see each thread does discardPebble() and drawnPebble() but they do it not synchronized. Also they start at the different time so first thread executes run() while another Thread hasn't started yet. How can i make them start at the same time and wait until all threads have done discardPebble() and drawnPebble() and then start again? I've read about CountDownLatches yesterday but didn't really understand how can I use them in my situation but I believe it can solve my problem.

PeppyReerry
  • 23
  • 2
  • 6
  • https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html – spectacularbob Nov 21 '17 at 16:51
  • 1
    There are dozens, if not hundreds of tutorials on Java concurrency. [This](https://docs.oracle.com/javase/tutorial/essential/concurrency/) is one example. Please take the tutorials to learn about multi-threaded programming. – Jim Garrison Nov 21 '17 at 16:52

0 Answers0