国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java基本教程之Thread中start()和run()的區(qū)別 java多線程教程

2019-11-26 15:47:01
字體:
供稿:網(wǎng)友

Thread類包含start()和run()方法,它們的區(qū)別是什么?本章將對此作出解答。本章內(nèi)容包括:
start() 和 run()的區(qū)別說明
start() 和 run()的區(qū)別示例
start() 和 run()相關(guān)源碼(基于JDK1.7.0_40)

start() 和 run()的區(qū)別說明
start() : 它的作用是啟動一個新線程,新線程會執(zhí)行相應(yīng)的run()方法。start()不能被重復(fù)調(diào)用。
run()   : run()就和普通的成員方法一樣,可以被重復(fù)調(diào)用。單獨(dú)調(diào)用run()的話,會在當(dāng)前線程中執(zhí)行run(),而并不會啟動新線程!

 

下面以代碼來進(jìn)行說明。

復(fù)制代碼 代碼如下:

class MyThread extends Thread{ 
    public void run(){
        ...
    }
};
MyThread mythread = new MyThread();

mythread.start()會啟動一個新線程,并在新線程中運(yùn)行run()方法。
而mythread.run()則會直接在當(dāng)前線程中運(yùn)行run()方法,并不會啟動一個新線程來運(yùn)行run()。

 

start() 和 run()的區(qū)別示例
下面,通過一個簡單示例演示它們之間的區(qū)別。源碼如下:

復(fù)制代碼 代碼如下:

public synchronized void start() {
    // 如果線程不是"就緒狀態(tài)",則拋出異常!
    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    // 將線程添加到ThreadGroup中
    group.add(this);

    boolean started = false;
    try {
        // 通過start0()啟動線程
        start0();
        // 設(shè)置started標(biāo)記
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
        }
    }
}

運(yùn)行結(jié)果:

復(fù)制代碼 代碼如下:

main call mythread.run()
main is running
main call mythread.start()
mythread is running

結(jié)果說明:
(01) Thread.currentThread().getName()是用于獲取“當(dāng)前線程”的名字。當(dāng)前線程是指正在cpu中調(diào)度執(zhí)行的線程。
(02) mythread.run()是在“主線程main”中調(diào)用的,該run()方法直接運(yùn)行在“主線程main”上。
(03) mythread.start()會啟動“線程mythread”,“線程mythread”啟動之后,會調(diào)用run()方法;此時的run()方法是運(yùn)行在“線程mythread”上。

 

start() 和 run()相關(guān)源碼(基于JDK1.7.0_40)
Thread.java中start()方法的源碼如下:

復(fù)制代碼 代碼如下:

public synchronized void start() {
    // 如果線程不是"就緒狀態(tài)",則拋出異常!
    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    // 將線程添加到ThreadGroup中
    group.add(this);

    boolean started = false;
    try {
        // 通過start0()啟動線程
        start0();
        // 設(shè)置started標(biāo)記
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
        }
    }
}

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

復(fù)制代碼 代碼如下:

private native void start0();


Thread.java中run()的代碼如下:

復(fù)制代碼 代碼如下:

public void run() {
    if (target != null) {
        target.run();
    }
}

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

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 榕江县| 长宁县| 浮山县| 乌鲁木齐县| 菏泽市| 二连浩特市| 阜南县| 巍山| 永泰县| 绥阳县| 海城市| 浦江县| 民乐县| 广西| 花莲市| 五寨县| 白朗县| 古蔺县| 海安县| 澜沧| 黎川县| 澳门| 修武县| 台湾省| 磴口县| 南投市| 东阳市| 南丰县| 绿春县| 祁连县| 巴东县| 凤台县| 会昌县| 措美县| 青铜峡市| 怀来县| 桃源县| 塔城市| 临沂市| 安塞县| 靖州|