I've been fiddling with creating a thread on which the rendering runs, and I've come across this way of implementing it:
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()
}
Note that only the sections of the code that are related to threads have been included.
Now, the program flow looks something like this (correct me if I'm wrong): Construct new object of type/class Main (hence, reserve a place on the heap). Then, the start() method of object of type Main is called. running boolean is set to true. Then, a new thread is created via constructor Thread (Runnable target, String name) - in my case, the first parameter is this keyword, meaning that the reference of the object of type Main is passed as the first parameter (since the method has been called by the object of type Main). Then, the next line is what fiddles me the most. The thread reference calls the method start(), but it somehow refers to the run() method. How?
I'd be very thankful for a thorough explanation of how start() method for a thread object can refer to the run() method.
You create a new Thread
with a Runnable
target of this
(the instance of Main
class). Main implements Runnable
means the method run()
is overridden. The Thread
class itself implements Runnable
.
When you start the thread with the configuration above, the method start()
causes the thread to begin execution; the Java Virtual Machine then calls the Thread
object's run()
method. It's said in the documentation. If you are curious, see the source code of the java.lang.Thread.
You can achieve the same effect with a simpler approach:
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");
}
}