Java 函数在时间过去后结束

Cod*_*Guy 3 java timer

这就是我想要做的。给定一个函数

public void foo() {

}
Run Code Online (Sandbox Code Playgroud)

我想让它在经过一定时间后结束。也就是说,想象一下这是某种随机生成器,它必须生成满足一些困难约束的随机对象,因此它可能会或可能不会在给定的时间分配下成功。也就是说,函数实际上可能是这样的

public void foo() {
   //task1
   while(fails) {
     //...
   }

   //task2
   while(fails2) {
      //...
   }

   //more tasks may follow, which use the data from the previous tasks to further try to satisfy difficult conditions
}
Run Code Online (Sandbox Code Playgroud)

这只是一个例子。但关键是该函数由许多 while 循环、许多测试用例和大量繁重的计算组成。

目标:我希望能够说“运行 foo(),如果 4 秒过去了并且 foo() 仍未完成,则立即停止 foo()”。

我尝试过的:我尝试在 foo() 的几乎每一行都包含条件,以查看已经过去了多少时间,并在 4 秒过后返回函数。但是考虑到 foo() 有多么复杂,这显然很难以代码方式进行,因为这需要在函数的每一行上测试时间。

我的思维逻辑:我认为这应该是可能的,因为有些函数会执行此类操作,无论状态如何都会终止代码,例如 System.exit(1)。这就是想法。我希望能够从外部调用以终止此函数 foo()。

Aar*_*ron 5

// foo method and global variables used
private static ArrayList<Integer> foo() {
    // info class
    class Info {
        public boolean run, completed;
        public ArrayList<Integer> list;
    }
    // declare info object, list
    final Info info = new Info();
    final Object wait = new Object();
    // run a new thread
    Thread t = new Thread(
        new Runnable() {
            // run method
            @Override
            public void run() {
                // setup run
                info.run = true;
                info.completed = false;
                info.list = new ArrayList<>();
                // loop to modify list. Don't put a big piece of code that will
                // take a long time to execute in here. 
                while(info.run) {
                    // example of what you should be doing in here:
                    info.list.add(1);
                    // and if you are done modifying the list, use:
                    break;
                }
                // done modifying list
                info.completed = true;
                synchronized(wait) {
                    wait.notify();
                }
            }
        }
    );
    t.start();
    // wait for four seconds, then return list
    try {
        synchronized(wait) {
            wait.wait(4000);
        }
    } catch (InterruptedException e) { e.printStackTrace(); }
    info.run = false;
    return info.completed ? info.list : null;
}
// main method
public static void main(String[] args) {
    // get list
    ArrayList<Integer> list = foo();
    System.out.println("Done!");
}
Run Code Online (Sandbox Code Playgroud)

foo() 方法有什么作用?

  1. 开始修改最终会返回的列表
  2. 如果修改此列表所花费的时间超过四秒,它将停止修改该列表并返回该列表。
  3. 如果列表提前停止,它将返回 null。
  4. 它现在只使用局部变量!
  5. 不错的奖励,它会在第二次修改完成后立即返回列表。