Reputation: 2244
I'm learning about the threads in Java. I want to know whether the following two pieces of code are the same:
class B extends Thread {
public void run() {
doSomething();
}
public void doSomething() {}
}
class A extends Thread {
public void run() {
new B().start();
}
}
The second piece of code is changing the class A:
class A extends Thread {
public void run() {
new B().doSomething();
}
}
When I read the code of my team's project, I find this problem: A thread invoking another thread without loop.
Upvotes: 0
Views: 73
Reputation: 42617
These two cases are not the same, as your question already suggests.
Assuming that in each case we enter the code by calling new A().start()
, then the first example starts a thread (A) which starts another thread (B) which calls doSomething()
.
The second case starts a single thread (A) which calls B.doSomething()
. In this case we don't start a thread of type B, because we never call .start()
on an instance of B.
Upvotes: 2
Reputation: 1568
In the first snippet you are actually creating a new thread and the invocation of doSomething() is in a separate thread to what A's run() method is running in,
In the second snippet you are execution B's doSomething() in the context (thread) that A is running in.
Upvotes: 0