Jason D'Souza
Jason D'Souza

Reputation: 1

Java Thread Stack Allocation For One Thread Calling Another Thread Class's Function

I'm trying to understand what function goes on which thread stack. Let's say Class A extends Thread, and has a method add(). If add() is called from within run(), then I assume it would be added on top of A's thread stack, but please correct me if I'm wrong. Now, what if A is running, but another Thread B call's A's add() method. Would that function be added to B's stack or A's stack. I'm new to concurrent programming so sorry if this question doesn't make any sense.

Upvotes: 0

Views: 37

Answers (1)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

It is recommended not to extend Thread in most situations. Classes that extend thread don't behave any differently to those that don't.

So let's modify the question. Suppose, class A implements Runnable and additionally has a method add. Clearly the method add has absolutely nothing to do with threads. add is executed on the same thread as the method that called it.

Similar run (whether in Thread or Runnable) runs in the thread that called it. That's why you call Thread.start - calling Thread.run is pointless.

Upvotes: 2

Related Questions