Reputation: 267
I created a test program uses threads:
class First implements Runnable {
public void run() {
System.out.print("One ");
}
}
class Second implements Runnable {
Thread other;
Second(Thread t) {other = t;}
public void run() {
System.out.print("Two");
}
}
public class ThreadTest {
void go() {
First first = new First();
Thread t = new Thread(first);
Second second = new Second(t);
Thread u = new Thread(second);
t.start();
u.start();
}
public static void main(String[] args) {
new ThreadTest().go();
}
}
I expected that it will print:
One One
But it suddenly for me had printed:
One Two
I don't understand why this is happening. I thought that in both threads, the method run()
from First class must be called. Because I passed First instance into Thread constructor and then pass this created thread into Second constructor. So method run()
from First class has priority over run()
method from Second class. Where am I wrong?
Upvotes: 0
Views: 66
Reputation: 178333
There is no reason why the second thread should print "One"
. It may have a reference to the first Thread
, but it does nothing with it. Nothing overrides Second
's run
method, so it just prints Two
.
To make the second Thread
print One
, have run
call the other Thread
's run
method.
class Second implements Runnable {
Thread other;
Second(Thread t) {other = t;}
public void run() {
other.run();
}
}
But it's unusual to call one Thread
's run
method from the run
method of another Thread
. In fact, it's unusual to call run
directly at all.
Upvotes: 2
Reputation: 116918
I expected that it will print: One One But it suddenly for me had printed: One Two
You are starting 2 threads. The First.run()
method prints out "One". The Second.run()
method prints out "Two". Just because you assign other = t;
in the Second
constructor does not change it's run()
method.
Because I passed First instance into Thread constructor and then pass this created thread into Second constructor. So method run() from First class has priority over run() method from Second class. Where am I wrong
Maybe in the Second.run()
method you meant to call other.run()
or something? That would be a strange pattern however that is not recommended. You should not link Thread
classes like that. You should probably pass in the First
method and then do:
class Second implements Runnable {
First first;
Second(First first) { this.first = first; }
public void run() {
first.run();
}
}
But even then, it is a bit of a strange pattern to call one run()
method from another.
Upvotes: 1