简体   繁体   English

Java如何知道void方法何时完成其方法体?

[英]How does Java know when a void method has finished its method body?

Let's say I have some code: 假设我有一些代码:

public int doSomething(int x)
{
    otherMethod(x);
    System.out.println("otherMethod is complete.");
    return 0;
}

public void otherMethod(int y)
{
    //method body
}

Since otherMethod's return type is void, how does the doSomething method know when otherMethod has completed, so it can go to the next like and print " otherMethod is complete."? 由于otherMethod的返回类型为void, doSomething方法如何知道otherMethod完成,因此它可以转到下一个类似并打印“ otherMethod is complete”。

EDIT: Added return 0; 编辑:添加return 0; to doSomething method so the example code will compile. to doSomething方法所以示例代码将编译。

The parser knows where the end of execution is and even adds a return, for example: 解析器知道执行结束的位置,甚至添加一个返回,例如:

 public static void main(String args[])  {

}

compiles to: 编译为:

 public static main([Ljava/lang/String;)V
   L0
    LINENUMBER 34 L0
    RETURN <------ SEE?
   L1
    LOCALVARIABLE args [Ljava/lang/String; L0 L1 0
    MAXSTACK = 0
    MAXLOCALS = 1
}

And the same applies to your code (though I've added in the return 0 since your code doesn't compile): 这同样适用于您的代码(尽管我已经在返回0中添加了代码,因为您的代码无法编译):

 public int doSomething(int x)
    {
        otherMethod(x);
        System.out.println("otherMethod is complete.");
        return 0;
    }

    public void otherMethod(int y)
    {
        //method body
    }

compiled code: 编译代码:

public doSomething(I)I
   L0
    LINENUMBER 38 L0
    ALOAD 0
    ILOAD 1
    INVOKEVIRTUAL TestRunner.otherMethod (I)V
   L1
    LINENUMBER 39 L1
    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    LDC "otherMethod is complete."
    INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V
   L2
    LINENUMBER 40 L2
    ICONST_0
    IRETURN
   L3
    LOCALVARIABLE this LTestRunner; L0 L3 0
    LOCALVARIABLE x I L0 L3 1
    MAXSTACK = 2
    MAXLOCALS = 2

  // access flags 0x1
  public otherMethod(I)V
   L0
    LINENUMBER 46 L0
    RETURN <-- return inserted!
   L1
    LOCALVARIABLE this LTestRunner; L0 L1 0
    LOCALVARIABLE y I L0 L1 1
    MAXSTACK = 0
    MAXLOCALS = 2
}

Because of the ending bracket. 因为结束括号。 Once the thread gets to the end of the method, it will return. 一旦线程到达方法的末尾,它将返回。 Additionally, the programmer can specify when a void method is finished by writing return; 另外,程序员可以通过写return;来指定何时完成void方法return;

Edit: I got the question mixed up. 编辑:我把问题搞砸了。 The Thread executes one method at a time, one statement at a time, so once the thread is finished a method it will go to the next line in the calling method. Thread一次执行一个方法,一次一个语句,所以一旦线程完成一个方法,它将转到调用方法的下一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM