在Java中等待函数

所以我正在编写一个Java代码来表示堆排序并表示我需要一个等待函数的操作,该函数将在不同的操作之间等待,但我不确定Java中是否有一个函数可以执行此操作,或者我是否需要我自己写这个函数,我该怎么做。

代表堆运动是一项功课,但写等待function并非如此,我感谢您的帮助

你正在寻找Thread.sleep(int milliseconds)

如果我理解你,你想在不同的任务执行上创建并行性,然后等待所有这些的完成继续。 这是你想要的吗? 如果你的回答是“是”,那么也许你可以使用“fork / join”框架(Java 7)

这是一段代码片段,摘自Brian Goetz(IBM Java guru)文章:

 public class MaxWithFJ extends RecursiveAction { private final int threshold; private final SelectMaxProblem problem; public int result; public MaxWithFJ(SelectMaxProblem problem, int threshold) { this.problem = problem; this.threshold = threshold; } protected void compute() { if (problem.size < threshold) result = problem.solveSequentially(); else { int midpoint = problem.size / 2; MaxWithFJ left = new MaxWithFJ(problem.subproblem(0, midpoint), threshold); MaxWithFJ right = new MaxWithFJ(problem.subproblem(midpoint + 1, problem.size), threshold); coInvoke(left, right); result = Math.max(left.result, right.result); } } public static void main(String[] args) { SelectMaxProblem problem = ... int threshold = ... int nThreads = ... MaxWithFJ mfj = new MaxWithFJ(problem, threshold); ForkJoinExecutor fjPool = new ForkJoinPool(nThreads); fjPool.invoke(mfj); int result = mfj.result; } } 

否则,如果不想要任何并行性并且只想等待一段时间,请使用Thread.Sleep(int miliseconds)函数。

Thread.sleep()就是你要找的。

如果你是一个Java新手,它抛出的例外可能会让你感到困惑。 很可能你会想要传播它或丢弃它并使用Thread.currentThread()重置中断标志.inrupt()

你可以尝试Thread.sleep(1000);

它将使当前线程hibernate1000毫秒。

我一直在使用一种更简单(但可能不是更好)的睡眠方式:

 public static void sleep(int amt) // In milliseconds { long a = System.currentTimeMillis(); long b = System.currentTimeMillis(); while ((b - a) <= amt) { b = System.currentTimeMillis(); } } 

这基本上会导致程序正在执行的所有操作都停止,直到时间用完为止。 它也可能导致一些滞后。 你被警告了。

这里有一些更深入的内容:

 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } 

在这里,我们插入1000作为毫秒值,或者在运行其余代码之前等待1秒钟。 这适用于Java中的任何程序。