rspec/rules/S2438/java/rule.adoc

35 lines
957 B
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
While it is technically correct to use a ``++Thread++`` where a ``++Runnable++`` is called for, the semantics of the two objects are different, and mixing them is a bad practice that will likely lead to headaches in the future.
The crux of the issue is that ``++Thread++`` is a larger concept than ``++Runnable++``. A ``++Runnable++`` is an object whose running should be managed. A ``++Thread++`` expects to manage the running of itself or other ``++Runnables++``.
== Noncompliant Code Example
----
public static void main(String[] args) {
Thread r =new Thread() {
int p;
@Override
public void run() {
while(true)
System.out.println("a");
}
};
new Thread(r).start(); // Noncompliant
----
== Compliant Solution
----
public static void main(String[] args) {
Runnable r =new Runnable() {
int p;
@Override
public void run() {
while(true)
System.out.println("a");
}
};
new Thread(r).start();
----