Why is this an issue?
According to the Java API documentation:
There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the
run method of class Thread. An instance of the subclass can then be allocated and started…
The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An
instance of the class can then be allocated, passed as an argument when creating Thread, and started.
By definition, extending the Thread class without overriding the run
method doesn’t make sense, and implies that the contract of the
Thread
class is not well understood.
Noncompliant code example
public class MyRunner extends Thread { // Noncompliant; run method not overridden
public void doSometing() {...}
}
Exceptions
If run()
is not overridden in a class extending Thread
, it means that starting the thread will actually call
Thread.run()
. However, Thread.run()
does nothing if it has not been fed with a target Runnable
. The rule
consequently ignore classes extending Thread
if they are calling, in their constructors, the super(...)
constructor with a
proper Runnable
target.
class MyThread extends Thread { // Compliant - calling super constructor with a Runnable
MyThread(Runnable target) {
super(target); // calling super constructor with a Runnable, which will be used for when Thread.run() is executed
// ...
}
}