Java Reference
In-Depth Information
public void run() {
System.out.println("Child");
}
}
If a client runs the following code:
Worker w = new SubWorker();
w.startThread("thread");
the client may expect
Parent
and
Child
to be printed. However,
Child
is printed twice
because the overridden method
run()
is invoked both times that a new thread is started.
Compliant Solution
This compliant solution modifies the
SubWorker
class and removes the call to
su-
per.startThread()
:
public class SubWorker extends Worker {
@Override
public void startThread(String name) {
new Thread(this, name).start();
}
// ...
}
The client code is also modified to start the parent and child threads separately. This
program produces the expected output:
Worker w1 = new Worker();
w1.startThread("parent-thread");
Worker w2 = new SubWorker();
w2.startThread("child-thread");