JAVA:如何在特定时间后停止执行某个功能?

时间:2013-10-26 17:49:25

标签: java executorservice execution-time callable iterative-deepening

我想实现迭代深化(增量树构建)。这是我要问的代码的一部分:

        ExecutorService executorService = Executors.newSingleThreadExecutor();

        Set<Callable<Integer>> callables = new HashSet<Callable<Integer>>();

        callables.add(new Callable<Integer>() {
            public Integer call() throws Exception {
                iterativeDeepening(depthLimit, board);
                return -1;
            }
        });
        callables.add(new Callable<Integer>() {
            public Integer call() throws Exception {
                Thread.sleep(500);
                return 1;
            }
        });
        try{
            executorService.invokeAny(callables, 1000, TimeUnit.MILLISECONDS);
        }catch(TimeoutException | InterruptedException ex){
            executorService.shutdown();
        }

        executorService.shutdown();

从我读到的有关时间限制的invokeAny(),它应该在到达截止日期后立即执行其Callable对象。它适用于我长时间睡眠而不是我的函数iterativeDeepening(depthLimit,board)。如何使它与我的功能一起工作? 下面我将代码粘贴到此函数:

    public void iterativeDeepening(byte depthLimit, byte[] board){

    for(byte depth=1;depth<depthLimit;depth++){
        GameTree gameTree= new GameTree();
        byte[] tempBoard = new byte[14];
        for(byte i=0;i<14;i++){
            tempBoard[i] = board[i];
        }
        Node <byte[]> root= new Node<byte[]>(tempBoard, player);
        try {
            gameTree.buildGameTree(depth, root);
        } catch (OutOfMemoryError E) {
            gameTree.eraseGameTree(depth,root);
            System.gc();
        }

        MiniMax minimax = new MiniMax(player);
        move= minimax.selectMove(depth, root);

    }
}

如果您知道更好的方法,或知道如何成功停止执行我的功能,请告诉我。我还尝试了本主题中提到的Runnable接口: How to stop execution after a certain time in Java? 但它的工作方式也一样。

1 个答案:

答案 0 :(得分:1)

达到超时后,ExecutorService将尝试通过调用Thread.interrupt()来中断所有当前正在运行的任务。这将使每个线程处于中断状态。设置此状态时,sleep()退出。

添加此检查:

if(Thread.currentThread().interrupted()) {
    return;
}

你的职能部门应该完成这项工作。

为您提供线程终止的提示:

try{
    executorService.invokeAny(callables, 1000, TimeUnit.MILLISECONDS);
} catch(TimeoutException | InterruptedException ex){
    //... ignore
} finally {
    executorService.shutdown();
    executorService.awaitTermination(); <-- add this line if you want to wait for the computation to end
}

<强>更新

  

这不是解决方案,因为在循环中有一个函数gameTree.buildGameTree(depth,root);它本身有时需要比截止日期更长的时间。

据我所知,无法从外部中断此类功能。此功能应不时检查其状态。如果它是循环,请考虑在部分或全部迭代中检查状态。

相关问题