我有一个计时问题,我不知道如何解决。

在我的第二个循环中,显示卡循环,并且每个连接都启动一个名为cLookAtCardConnection的类。此类有时会设置标志mPlayerList.GetNextFlag(),从而导致循环退出,程序进入第一个循环,将卡翻转过来,从而调用类cLookAtCardConnection

问题是在设置mPlayerList.GetNextFlag()之后,接下来的几个连接仍处于同一循环中,并且在设置标志时进入类cLookAtCardConnection而不是(退出?)循环,并进入调用。

设置标志后,为什么退出循环会有延迟?

while( lBoard.Next()==true)
        {

        mPlayerList.Next();

        // inner loop wait for all players
        /////////////////////////////////////////////////////////////////////////////
        // turn one card over
         mPlayerList.WaitForAllPlayers();
            do
            {
                    do{
                        r=GetClient();
                        switch(r)
                        {
                        case 0: return; // exitvon a very bad error
                        }
                    } while(r==2);// loop if it was a timeout
                    cTurnCardOvrerConnection thread = new cLookAtCardConnection("thread3", connection, mPlayerList, mPlayersMessages, lBoard);

                } while( mPlayerList.AllPlayersFinished()==false);// end while

            //////////////////////////////////////////////////////////////////////////
            // Display card -LOOK AT CARD
            mPlayerList.ClearNextFlag();
             mPlayerList.WaitForAllPlayers();
            do
            {
                System.out.println(Thread.currentThread()+": Display card \r");
                    do{
                        r=GetClient();
                        switch(r)
                        {
                        case 0: return; // exitvon a very bad error
                        }
                    } while(r==2);// loop if it was a timeout
                    cLookAtCardConnection thread = new cLookAtCardConnection("thread3", connection, mPlayerList, mPlayersMessages, lBoard);

// after this flag is set the next couple connectons are still in this loop???
            } while( mPlayerList.GetNextFlag()==false);// end while

        } // reloop game board
    } // loop forever
    //      System.out.println("--------- Eit player loop ------------------- \r");

        } catch(IOException ec)
        {
            System.out.println(ec.getMessage());
        }



      } // end run

} // end of class

最佳答案

您可能需要设置一个synchronized块,以使do-while循环内的代码一次只能被单个线程访问。

09-16 11:50