首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 多線程基礎:Thread 中 start() 與 run() 的本質區別

     編輯:Java 相關知識

核心區別

方法作用能否重複調用是否啟動新線程
start()啟動新線程,新線程執行 run()否(拋出 IllegalThreadStateException)是
run()普通成員方法,直接在當前線程執行是否

代碼驗證

// Demo.java
class MyThread extends Thread {
    public MyThread(String name) { super(name); }
    public void run() {
        System.out.println(Thread.currentThread().getName() + " is running");
    }
}
public class Demo {
    public static void main(String[] args) {
        Thread mythread = new MyThread("mythread");
        System.out.println(Thread.currentThread().getName() + " call mythread.run()");
        mythread.run();      // 在 main 線程中直接執行
        System.out.println(Thread.currentThread().getName() + " call mythread.start()");
        mythread.start();    // 啟動新線程執行
    }
}

運行結果

main call mythread.run()
main is running          <-- run() 在 main 線程執行
main call mythread.start()
mythread is running      <-- run() 在新線程 mythread 執行

源碼級分析(JDK 1.7.0_40)

start()

public synchronized void start() {
    if (threadStatus != 0) throw new IllegalThreadStateException();
    group.add(this);
    boolean started = false;
    try {
        start0();        // 本地方法,真正啟動新線程
        started = true;
    } finally { ... }
}
private native void start0();

start0() 是 native 方法,會創建新線程並調用 run()。

run()

public void run() {
    if (target != null) {
        target.run();    // 直接調用 Runnable 的 run()
    }
}

target 是 Runnable 對象。run() 只是普通方法調用,不會創建新線程。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved