grg-n-sox
grg-n-sox

Reputation: 717

In Java, if I call a class that extends Thread from another runnable object, which Thread executes?

I am working on some concurrency programming and one part is bothering me.

Let's say I have some class Foo that extends Thread and implements it's own public method called bar() as well as the required run() method. If I implement multiple Foo objects, each one containing a reference to another Foo object, and inside the run() method for the Foo class is a call on the bar() method for whatever Foo object it has a reference to. If the Foo object with name "Thread-1" calls bar() on the Foo object with name "Thread-2", then who is actually executing the method code in "Thread-2"? Does execution get handed off from "Thread-1" to "Thread-2" to execute or does "Thread-1" continue executing code in "Thread-2"? If it is the second choice, how can I make it act like the first choice?

Upvotes: 0

Views: 1966

Answers (4)

Thomas
Thomas

Reputation: 5094

It will run on the thread that called it. Calling a method in a class that extends thread is no different than calling a method of any other class.

public class A extends Thread
{
     public void bar()
     {
         System.out.println(Thread.currentThread().getName());
     }

     public void run()
     {
         new A().bar();
     }

     public static void main()
     {
         A testA = new A();     
         testA.setName("parent");
         testA.start();        
     }
}

Should print 'parent';

Upvotes: 0

Michał Kosmulski
Michał Kosmulski

Reputation: 10020

Apart from being executed when you start the thread, run() is a normal method. If you manuallly call, it behaves like any other method, meaning it is executed inside the caller's thread.

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

Foo is just an object, imagine it does not extends Thread, what would you expect? As long as new thread is not start()ed, you are just calling an ordinary method, on behalf of the calling thread.

Moreover, if calling a method on a different Thread object would cause that thread taking over the execution, what would happen with the current thread's execution?

Upvotes: 0

Bozho
Bozho

Reputation: 597096

A new thread is started only if you invoke thread.start() (or use executor.submit(runnable)). All other method invocations remain in the current thread.

Upvotes: 4

Related Questions