多线程原理——随机打印结果


main方法的程序:


public class Demo01Tread {
    public static void main(String[] args) {

        MyThread mt=new MyThread();
        mt.start();
        for (int i = 0; i <20 ; i++) {
            System.out.println("main:"+i);
        }
    }
}
main方法中
 mt.start();

是重新开辟空间,然后调用后面的run方法。

 mt.run();

直接压栈,不重新开辟空间


run程序:
public class MyThread extends Thread {
    @Override
    public void run() {//重写run方法,设置run方法,设置线程任务
        for (int i = 0; i < 20; i++) {
            System.out.println("run:"+i);
        }
    }
}
cpu有两条路径随机运行start和run方法。

原文地址:https://www.cnblogs.com/cy2268540857/p/13734798.html