start() 方法从 start() 调用一个线程......令人困惑

start() method called for a thread from a start() ... confusing

我一直在摆弄创建一个渲染 运行s 的线程,我遇到了这种实现方式:

Class Main implements Runnable {
private Thread thread;
private boolean running = false;

public void start() {
            running = true;
    thread = new Thread(this, "renderingThread")
    thread.start(); //calls run()
}

    public void run() {

    init(); //init glfw + create window

    while(running) {
        update();
        render();
    }
}

    public static void main(String[] args) {
        new Main().start()
    }

请注意,仅包含与线程相关的代码部分。

现在,程序流程看起来像这样(如果我错了请纠正我):构造新对象type/class Main(因此,保留一个位置在堆上)。然后调用Main类型对象的start()方法。 运行ning 布尔值设置为真。然后,通过构造函数创建一个新线程 Thread (Runnable target, String name) - 在我的例子中,第一个参数是 this 关键字,意思是Main 类型的对象的引用作为第一个参数传递(因为该方法已被 Main 类型的对象调用)。然后,下一行是最让我烦恼的。 thread 引用调用方法 start(),但它以某种方式引用 运行() 方法。怎么样?

非常感谢您对线程对象的 start() 方法如何参考 运行() 方法。

看看 JavaDoc (https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#start--)

当在 Thread 对象上调用 start() 时,它会创建一个新线程并在该线程上调用 run() 方法。

您创建了一个新的 Thread,其 Runnable 目标为 thisMain class 的实例)。 Main implements Runnable 表示方法 run() 被覆盖。 Thread class 本身实现了 Runnable.

当您使用上述配置启动线程时,方法start() 会导致线程开始执行; Java 虚拟机然后调用 Thread 对象的 run() 方法。 documentation. If you are curious, see the source code of the java.lang.Thread.

中说

你可以用更简单的方法达到同样的效果:

public class Main implements Runnable { 

    @Override
    public void run() {
        System.out.println("New thread");
    }

    public static void main(String[] args) {
        new Thread(new Main()).start();
        System.out.println("Main thread");
    }
}