This rule raises an issue when Thread.run() is called instead of Thread.start().
The likely intention of a user calling Thread.run() is to start the execution of code within a new thread. This, however, is not what
happens when this method is called.
The purpose of Thread.run() is to provide a method that users can overwrite to specify the code to be executed. The actual thread is
then started by calling Thread.start(). When Thread.run() is called directly, it will be executed as a regular method within
the current thread.
If you intend to execute the contents of the Thread.run() method within a new thread, call Thread.start() instead.
If your intention is only to have a container for a method but execute this method within the current thread, do not use Thread but
Runnable or another functional interface.
Thread myThread = new Thread(runnable); myThread.run(); // Noncompliant, does not start a thread
Thread myThread = new Thread(runnable); myThread.start(); // Compliant
class ComputePrimesThread extends Thread {
@Override
public void run() {
// ...
}
}
new ComputePrimesThread().run(); // Noncompliant, does not start a thread
class ComputePrimesThread extends Thread {
@Override
public void run() {
// ...
}
}
new ComputePrimesThread().start(); // Compliant
class Button {
private Thread onClick;
Button(Thread onClick) {
this.onClick = onClick;
}
private void clicked() {
if (onClick != null) onClick.run(); // Noncompliant, use functional interface
}
}
new Button(new Thread() {
@Override public void run() {
System.out.println("clicked!");
}
});
class Button {
private Runnable onClick;
Button(Runnable onClick) {
this.onClick = onClick;
}
private void clicked() {
if (onClick != null) onClick.run(); // compliant
}
}
new Button(() -> System.out.println("clicked!"));