How can i loop 2 different threads?

Viewed 49

My program is basically playing Tic tac toe with 2 players which each one runs on a different thread. Now my problem is that i dont know how to keep running both threads one after another until one of the players win. This is my code:

            final HumanPlayer p1 = new HumanPlayer();
            final HumanPlayer p2 = new HumanPlayer();
            Thread tr1 = new Thread()
                {
                    public void run()
                    {
                        
                            System.out.printf("Player %s's turn\n",p1Name);
                            System.out.printf("Insert row number:\n");
                            row = Integer.parseInt(s.nextLine());
                            System.out.printf("Insert column number:\n");
                            col = Integer.parseInt(s.nextLine());
                            p1.fillBoard(p1.index(row,col),board,1);
                            p1.printBoard(board);   
                            if(p1.checkWin(board, p1Name) != null)
                            {
                                System.out.printf("Player %s won.\n",p1Name);
                            }
                        
                    }
                };
            Thread tr2 = new Thread()
            {
                public void run()
                {
                    
                        System.out.printf("Player %s's turn\n",p2Name);
                        System.out.printf("Insert row number:\n");
                        row = Integer.parseInt(s.nextLine());
                        System.out.printf("Insert column number:\n");
                        col = Integer.parseInt(s.nextLine());
                        p2.fillBoard(p2.index(row,col),board,2);
                        p2.printBoard(board);
                        if(p2.checkWin(board, p2Name) != null)
                        {
                            System.out.printf("Player %s won.\n",p2Name);
                        }
                    
                }
            };

                tr1.start();
                tr1.join();
                tr2.start();
                tr2.join();
        }
1 Answers

Change your launch sequence:

tr1.start();
tr2.start();
tr1.join();
tr2.join();

This will start both threads and then await until they're done doing work. You're still missing some essential pieces in your code like the while loop to keep solving until the game is done and synchronizing the turns between your threads which is off-scope of this current question.

Related