【问题标题】:How can i loop 2 different threads?我怎样才能循环2个不同的线程?
【发布时间】:2023-03-13 05:42:01
【问题描述】:

我的程序基本上是用 2 个玩家玩井字游戏,每个玩家在不同的线程上运行。现在我的问题是我不知道如何让两个线程一个接一个地运行,直到其中一个玩家获胜。这是我的代码:

            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();
        }

【问题讨论】:

    标签: java multithreading java-threads


    【解决方案1】:

    更改您的启动顺序:

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

    这将启动两个线程,然后等待它们完成工作。您仍然缺少代码中的一些重要部分,例如 while 循环以继续解决直到游戏完成并同步线程之间的轮次,这超出了当前问题的范围。

    【讨论】:

    • 我在每个 run() 中都有一个循环,一旦玩家获胜,它就会停止。问题是它不断循环同一个玩家,而从未到达第二个玩家。我现在就试试你建议的解决方案。
    • 它只是在我输入输入之前启动两个线程,然后崩溃。我发布的代码运行良好,但只运行一次。
    • 您需要同步两个线程来执行这样的任务,这是一项艰巨的任务。你发射了一个,然后另一个,这就是它起作用的原因。您的代码等待 Thread1 的执行完成,然后启动第二个。我无法说出您要实现的目标,但是您可以将每个线程的代码包装到一个方法中并执行以下操作:while(game.notWon() { pl1.makeMove(); pl2.makeMove(); } 不使用任何线程。多线程和任务同步不是一个简单的话题:)
    猜你喜欢
    • 2021-07-14
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    • 2021-09-27
    • 2017-06-25
    • 2020-06-07
    相关资源
    最近更新 更多