直接调用 run() 方法¶
ID: java/call-to-thread-run
Kind: problem
Security severity:
Severity: recommendation
Precision: high
Tags:
- reliability
- correctness
- concurrency
- external/cwe/cwe-572
Query suites:
- java-security-and-quality.qls
对 Thread
对象的 run
方法的直接调用不会启动一个单独的线程。该方法在当前线程内执行。这是一种不常见的用法,因为 Thread.run()
通常旨在从一个单独的线程内调用。
建议¶
要在单独的线程内执行 Runnable.run
,请执行以下操作之一
使用
Runnable
对象构造一个Thread
对象,并在Thread
对象上调用start
。定义
Thread
对象的一个子类,并覆盖其run
方法的定义。然后构造此子类的实例,并直接在该实例上调用start
。
示例¶
在以下示例中,主线程 ThreadDemo
使用 run
调用子线程 NewThread
。这会导致子线程在执行完主线程的其余部分之前运行完成,因此“子线程活动”在“主线程活动”之前打印出来。
public class ThreadDemo {
public static void main(String args[]) {
NewThread runnable = new NewThread();
runnable.run(); // Call to 'run' does not start a separate thread
System.out.println("Main thread activity.");
}
}
class NewThread extends Thread {
public void run() {
try {
Thread.sleep(10000);
}
catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Child thread activity.");
}
}
要让这两个线程同时运行,请创建子线程并调用 start
,如下所示。这会导致主线程在子线程等待时继续运行,因此“主线程活动”在“子线程活动”之前打印出来。
public class ThreadDemo {
public static void main(String args[]) {
NewThread runnable = new NewThread();
runnable.start(); // Call 'start' method
System.out.println("Main thread activity.");
}
}