有一个代码作为初级Java开发人员的任务给出.我在五年内使用Java,这段代码让我很困惑:
public class Main {
String variable;
public static void main(String[] args) {
System.out.println("Hello World!");
B b = new B();
}
public Main(){
printVariable();
}
protected void printVariable(){
variable = "variable is initialized in Main Class";
}
}
public class B extends Main {
String variable = null;
public B(){
System.out.println("variable value = " + variable);
}
protected void printVariable(){
variable = "variable is initialized in B Class";
}
}
Run Code Online (Sandbox Code Playgroud)
输出将是:
Hello World!
variable value = null
Run Code Online (Sandbox Code Playgroud)
但如果我们改变String variable …
突然发现 suspend 函数的递归调用比调用同一个函数但没有suspend修饰符要花费更多的时间,所以请考虑下面的代码片段(基本的斐波那契数列计算):
suspend fun asyncFibonacci(n: Int): Long = when {
n <= -2 -> asyncFibonacci(n + 2) - asyncFibonacci(n + 1)
n == -1 -> 1
n == 0 -> 0
n == 1 -> 1
n >= 2 -> asyncFibonacci(n - 1) + asyncFibonacci(n - 2)
else -> throw IllegalArgumentException()
}
Run Code Online (Sandbox Code Playgroud)
如果我调用此函数并使用以下代码测量其执行时间:
fun main(args: Array<String>) {
val totalElapsedTime = measureTimeMillis {
val nFibonacci = 40
val deferredFirstResult: Deferred<Long> = async {
asyncProfile("fibonacci") { asyncFibonacci(nFibonacci) } as …Run Code Online (Sandbox Code Playgroud)