如何设置方法的最长执行时间?

时间:2016-12-03 13:30:15

标签: java executorservice

我有一个用Java编写的数独游戏。游戏的主要过程是主要方法。我有一个while循环,其中我有myClassObject.getCommandFromScanner()函数来读取Scanner的输入,因此用户可以填充数独板上的空位置或从菜单中选择其他选项(例如save,show solution和exit to main菜单)。只有当用户选择退出菜单时,此循环才会结束,因为函数myClassObject.getCommandFromScanner()仅在这种情况下返回false。我想设置游戏的指定时间,但不能在while循环中执行(while((System.currentTimeMillis() - nGame.timeAtStart< 10000)&& myClassObject.getCommandFromScanner()))< - for第一次第一个条件为真,循环可以等待用户输入打开和打开。只有当用户输入内容时,循环条件才会再次chceck,然后退出此循环。我怎么解决这个问题?我也尝试使用ExecutorService它几乎工作,循环执行指定的时间,但然后它退出到菜单,用户无法启动新游戏。扫描仪停止正常工作,我的主窗口与游戏崩溃...我是新来的,很抱歉,如果我的问题不够清楚。我希望你能帮助我

public class Sudoku
{
public static void main(String[] args) throws Exception
{        
while(course != exit)
{
    opt = new String(in.next());
    int option;

    option = Character.getNumericValue(opt.codePointAt(0));

    if(course == menu)
    {
        //go to menu
    }

    else if(course == newGame)
    {
        //setup new game
    }

    if(course == game)
    {
        nGame.timeAtStart=System.currentTimeMillis();
        myClassObject.setGame(newGame);

        ExecutorService executor = Executors.newFixedThreadPool(1);
        Future<?> future = executor.submit(new Runnable() {
            @Override
            public void run() {
                try{
                    while(myClassObject.getCommandFromScanner());
                }
                catch(Exception e) {}
            }
        });

        executor.shutdown();

        try {
            future.get(8, TimeUnit.SECONDS);  //
        } catch (InterruptedException e) {    //
            System.out.println("job was interrupted");
        } catch (ExecutionException e) {
            System.out.println("caught exception: " + e.getCause());
        } catch (TimeoutException e) {
            future.cancel(true); 
            System.out.println("Your game timed out!");
        }

        course.printMessage("TIMEOUT");
        course = menu;

    }
}
}
}

这是我的代码的原始版本:

public class Sudoku
{
public static void main(String[] args) throws Exception
{        
while(course != exit)
{
    opt = new String(in.next());
    int option;

    option = Character.getNumericValue(opt.codePointAt(0));

    if(course == menu)
    {
        //go to menu
    }

    else if(course == newGame)
    {
        //setup new game
    }

    if(course == game)
    {
        nGame.timeAtStart=System.currentTimeMillis();
        myClassObject.setGame(newGame);
        while(myClassObject.getCommandFromScanner()); //while user don't choose 'menu' option, read input from keyboard
        course = menu; //user choose 'menu', go to menu section

    }
   }
  }

} 我想设置游戏的最长时间,然后显示消息:“超时”并转到主菜单

1 个答案:

答案 0 :(得分:0)

TimerTask可能有所帮助:

TimerTask task = new TimerTask()
{
    public void run()
    {
        if( str.equals("") )
        {
            System.out.println( "TimeOut. exit..." );
            System.exit( 0 ); //or other operation.
        }
    }    
};
Timer timer = new Timer();
timer.schedule(task, 10*1000 );  //10 seconds
String cmd = myClassObject.getCommandFromScanner();
timer.cancel();  //if not timeout ,cancle it.
System.out.println( "you have entered: "+ cmd );

价:https://stackoverflow.com/a/5854048/6037575

更新:

设置整场比赛的超时时间:

static void main(){
...
// ready to start the game
TimerTask task = new TimerTask()
{
    public void run()
    {

            System.out.println( "TimeOut.Return to the mani menu." );
            course = menu; // how to return main menu is dependent on you

    }    
};

while(true){
//  Here the user is playing the game.
// and if he can work it out before timeout
// you should do something else to end the game.
}

很抱歉,我无法为您提供真正的代码,这些代码只能依赖于您提供的代码,但我认为只有一些伪代码可能是可行的解决方案。