我正在学习java中的MULTITHREADING,我想知道为什么在下面的代码中,当执行start方法调用子线程中的run方法时,子线程没有立即运行?
相反,在执行 start 方法后,主线程继续执行其代码并开始打印“.”。它做了三遍,控制权由子线程接管。然后子线程执行一次它的代码并返回到主线程。然后主线程完成,然后子线程也完成其执行。
我无法理解为什么会这样?
class MyThread implements Runnable {
String thrdName;
MyThread(String name) {
thrdName = name;
}
public void run() {
System.out.println(thrdName + " starting.");
for (int count = 0; count < 10; count++) {
System.out.println("In " + thrdName + ", count is " + count);
}
}
}
class UseThreads {
public static void main(String args[]) {
System.out.println("Main thread starting.");
MyThread mt = new MyThread("Child #1");
Thread newThrd = new Thread(mt);
newThrd.start();
for (int i = 0; i < 50; i++) {
System.out.print(".");
}
}
}