Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method of a class which extends Thread, from another class

I know this is a bit naive question but I want to understand the basic working principle behind multi-threading in java. Consider the following code and say A is executed in Main thread and it starts execution of another worker thread ,defined in class B. I want to know that can B.func1 called from A and run method of B, be executed in parallel or not?

public class A {
    public static void main(String[] args) {
        B obj = new B();
        obj.start();
        obj.func1();
    }
}

public class B extends Thread {
    public B() {
        //constructor
    }
    public void run() {
        while(true) {
            //do somethings
        }
    }
    public void func1() {
        //do someotherthings
    }
}
like image 651
PHcoDer Avatar asked Feb 07 '23 20:02

PHcoDer


1 Answers

There is no magic behind a method call. If you call method from a thread, it is called in exactly the same thread. So since obj.func1() is called from main, it will be run in the main thread. It doesn't matter which class it belongs to or whether or not it extends Thread.

The new thread starts by executing run. Everything called from run and so on will be executed in parallel to main.

like image 177
Sergei Tachenov Avatar answered Feb 09 '23 13:02

Sergei Tachenov