0

I have a question about the run method in Java, i know that when we call start() method a "stack" is created in JVM memory and that is the place where the run() method start its execution, but which object is used to call this method in the code below, the thread object(t1) or the runnable object(obj) that I have passed in?

I have trouble understanding this.

public class A implements Runnable {
    
    public void run() {
        System.out.println("....");
    }
    
    public static void main(String[] args) {
        A obj = new A();
        Thread t1 = new Thread(obj);
        t1.start();
    }
}
Hendrik
  • 5,085
  • 24
  • 56
Carl h
  • 23
  • 4
  • Look at the source code for class `Thread`. – Abra Feb 21 '21 at 19:51
  • 1
    I'm not sure that it was appropriate to close this question as a duplicate. What did you mean when you asked, "which object is used to call this method...?" Objects don't call methods. _Methods_ call methods. Did you really mean to ask which _class_ owns the method that called your `run()` method? or were you asking which object is `this` inside of the `run()` invocation? In either case that's not a dupe of the "start() vs. run()" question. You should re-ask it and try to be a bit more explicit about what is confusing you. – Solomon Slow Feb 22 '21 at 13:17
  • P.S., The best questions to ask here are ones where you include output from your program that you don't understand or, an error message that you got from the build system that you don't understand. If you show the code and the output or error message, then usually somebody can clear up the misunderstanding. But, if the program does what you expected it to do, asking _why_ it did what you expected, is a much broader question. It invites vague, unfocused answers that don't have much potential to help other readers. – Solomon Slow Feb 22 '21 at 13:21
  • @SolomonSlow yeah that's what i was trying to ask in that question, which object is this inside of the run() invocation, mby i have misunderstood that concept, cause i was thinking that "this" is the object from which the method name is used to call the method body – Carl h Feb 23 '21 at 14:37
  • 1
    Your `run()` method is declared in `class A`. The `this` object must always be an instance of `class A` or, an instance of some class that directly or indirectly `extends class A`. (The same would be true for `this` in any method `m(...)` that belongs to any `class C`.) In your example, it's the `A` instance that was created in `main(...)` and assigned to the local variable, `obj`. – Solomon Slow Feb 23 '21 at 15:50

2 Answers2

0

The run() method is called by the thread t1, after you call the thread's start() method.

Hendrik
  • 5,085
  • 24
  • 56
0

It is the object of Thread which calls run() method internally.

Srijan
  • 100
  • 1
  • 6