什么时候在Java中调用Thread.run()而不是Thread.start()?
当我们在线程上调用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
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语