Java基礎加強之並發(三)Thread中start()和run()的區別

來源:互聯網
上載者:User

標籤:out   pre   group   java   dstat   標記   col   exception   ext   

Thread中start()和run()的區別

start() : 它的作用是啟動一個新線程,新線程會執行相應的run()方法。start()不能被重複調用。
run()   : run()就和普通的成員方法一樣,可以被重複調用。單獨調用run()的話,會在當前線程中執行run(),而並不會啟動新線程!

MyThreadTest.java代碼

class MyThread extends Thread{    public void run() {        System.out.println("線程名:"+Thread.currentThread().getName());    }}public class MyThreadTest {    public static void main(String[] args) {        MyThread mythread = new MyThread();        mythread.start();//運行結果:線程名:Thread-0        mythread.run();//運行結果:線程名:main    }}

結果說明
(01) Thread.currentThread().getName()是用於擷取“當前線程”的名字。當前線程是指正在cpu中調度執行的線程。
(02) mythread.run()是在“主線程main”中調用的,該run()方法直接運行在“主線程main”上。
(03) mythread.start()會啟動“線程mythread”,“線程mythread”啟動之後,會調用run()方法;此時的run()方法是運行在“線程mythread”上。

Thread類中start()方法源碼
public synchronized void start() {    // 如果線程不是"就緒狀態",則拋出異常!    if (threadStatus != 0)        throw new IllegalThreadStateException();    // 將線程添加到ThreadGroup中    group.add(this);    boolean started = false;    try {        // 通過start0()啟動線程        start0();        // 設定started標記        started = true;    } finally {        try {            if (!started) {                group.threadStartFailed(this);            }        } catch (Throwable ignore) {        }    }}

說明:start()實際上是通過本地方法start0()啟動線程的。而start0()會新運行一個線程,新線程會調用run()方法。

Thread類中run源碼
private Runnable target;
public void run() { if (target != null) { target.run(); }}

說明:target是一個Runnable對象。run()就是直接調用Thread線程的Runnable成員的run()方法,並不會建立一個線程。

 

Java基礎加強之並發(三)Thread中start()和run()的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.