Prefer Implementing Runnable Over Extending Thread
ID |
java.prefer_runnable_over_thread |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
best-practice, concurrency |
Rationale
Extending Thread couples the task logic with the threading mechanism. Since Java only supports single inheritance, extending Thread also prevents the class from extending any other class. Implementing Runnable (or Callable) instead allows the task to be decoupled from the execution mechanism and submitted to an ExecutorService or thread pool.
// Bad -- extends Thread
class Worker extends Thread {
public void run() {
doWork();
}
}