当我们在线程上调用start()方法时,它将导致线程开始执行,并且Java虚拟机(JVM)会调用线程的run()方法。如果直接调用run()方法,它将被视为线程类(或可运行接口)的常规 重写方法,它将在当前线程的上下文中执行,而不是在新线程中执行。
public class CallRunMethodTest extends Thread {
@Override
public void run() {
System.out.println("In the run() method: " + Thread.currentThread().getName());
for(int i = 0; i < 5 ; i++) {
System.out.println("i: " + i);
try {
Thread.sleep(300);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
public static void main(String[] args) {
CallRunMethodTest t1 = new CallRunMethodTest();
CallRunMethodTest t2 = new CallRunMethodTest();
t1.run(); // calling run() method directly instead of start() method t2.run(); // calling run() method directly instead of start() method }
}在上面的示例中,创建了两个线程,并且run()直接在线程上调用start()方法,而不是调用方法。
输出结果
In the run() method: main i: 0 i: 1 i: 2 i: 3 i: 4 In the run() method: main i: 0 i: 1 i: 2 i: 3 i: 4