I am designing a Card based Game in Java. I have implemented the game logic. It is working fine. Now I want to add a functionality which can check for the time player is playing the game. If the time goes above a threshold limit, I want to terminate the Execution of Game. Please suggest me what should be the best strategy to implement this feature? Is creating a Thread and checking the time a good technique or there is any other technique to achieve this?
Edit: Sorry for the vague description.What I want to implement is, no matter where the player is in the execution sequence, when the time limit reaches, program should terminate. If i implement the check at the looping condition, then if the time is still left, program will continue and complete the set of instructions in the loop, but if the time is over even if the program is entered into the execution loop, it should stop doing whatever it is doing. This is what i want to implement.
Thanks,
Tara Singh
I guess checking the elapsed time here and there would be sufficient, but if you want to use threading, here is a simple way to do it. You can also use
Timerinstead of creating your own thread. The idea is same;TimerTaskshould interrupt the main thread when the timeout happens.and then
Using the interruption flag is the preferred way to solve this kind of problem. One of the advantage of using interruption flag instead of creating your own signaling flag, or checking for elapsed time in the loop itself is that you can utilize the interruption support of other APIs.
For example, you might use
Thread.sleep()in your game. If you don’t use the interruption mechanism, you must wait untilsleep()returns. If you do use the interruption mechanism,sleep()will immediately return, throwingInterruptedException, so your app. will be more responsive.Whenever you catch
InterruptedExceptionin your app. handle it as follows unless you have specific reasons:Whenever the app. throws
InterruptedExceptionyou have to “restore” the interruption flag in order to relay the interruption message up the stack becauseInterruptedExceptionwill “clear” the interruption flag (to false).