什么时候在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 档案调动孩子祝福语简短