我正在学习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(".");
}
}
}
最佳答案
当您在线程上调用 start()
时,您无法保证它的启动速度。这取决于您计算机的线程调度程序。如果多次运行代码,您的线程可能会获得几种不同的执行顺序。
关于java多线程-子线程不会立即启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11874735/