什么时候在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 送给学长毕业祝福语简短