下面看一个示例。

    1. 编写一个类,通过 run 方法调用线程 ```java package thread;

    public class ThreadTest { private static void attack() { System.out.println(“Fight”); System.out.println(“Current Thread is: “ + Thread.currentThread().getName()); }

    1. public static void main(String[] args) {
    2. Thread t = new Thread() {
    3. @Override
    4. public void run() {
    5. attack();
    6. }
    7. };
    8. System.out.println("current main thread is: " + Thread.currentThread().getName());
    9. t.run();
    10. }

    }

    ![image.png](https://cdn.nlark.com/yuque/0/2021/png/390086/1617445057980-262e58a9-05b8-47c4-9501-c2cb16cab162.png#align=left&display=inline&height=88&margin=%5Bobject%20Object%5D&name=image.png&originHeight=88&originWidth=230&size=3940&status=done&style=none&width=230)
    
    2. 编写一个类,通过 start 方法调用线程
    ```java
    package thread;
    
    public class ThreadTest {
        private static void attack() {
            System.out.println("Fight");
            System.out.println("Current Thread is: " + Thread.currentThread().getName());
        }
    
        public static void main(String[] args) {
            Thread t = new Thread() {
                @Override
                public void run() {
                    attack();
                }
            };
    
            System.out.println("current main thread is: " + Thread.currentThread().getName());
            t.start();
        }
    }
    

    image.png
    调用 run 会继续使用主线程来执行方法,而用 start 的时候则会用一个非 main 的线程来执行方法。
    下面看一下 start 的源码。
    image.png
    进入到 start0 方法
    image.png
    发现其是一个 native 方法
    image.png
    start0 调用的是 JVM_StartThread 方法
    image.png
    image.png
    通过这里我们发现这里会创建新的线程
    image.png
    这里会告诉虚拟机执行 run 方法里的内容
    image.png
    start 方法会调用 JVM 的 StartThread 方法来创建新的子线程,并通过 thread_entry 方法去调用 run 方法

    • 调用 start() 方法会创建一个新的子线程并启动
    • run() 方法只是 Thread 的一个普通方法的调用