Java多線程start()方法原理解析
1、為什么啟動線程不用run()方法而是使用start()方法
run()方法只是一個類中的普通方法,調(diào)用run方法跟調(diào)用普通方法一樣
而start()是創(chuàng)建線程等一系列工作,然后自己調(diào)用run里面的任務(wù)內(nèi)容。
驗證代碼:
/**
* @data 2019/11/8 - 下午10:29
* 描述:run()和start()
*/
public class StartAndRunMethod {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
};
runnable.run();
new Thread(runnable).start();
}
}
結(jié)果:
main
Thread-0
2、start()源碼解讀
啟動新線程檢查線程狀態(tài)
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
關(guān)于threadStatus源碼:
/* * Java thread status for tools, default indicates thread 'not yet started' */ private volatile int threadStatus;
通過代碼可以看到就是threadStatus就是記錄Thread的狀態(tài),初始線程默認為0.
加入線程組
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
調(diào)用start0()
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
start0()方法使用c++編寫的方法,這些代碼在gdk代碼中,所以這里不再這里探究了。
3、start()方法不能使用多次
通過剛剛源碼分析,就知道start方法剛開始就檢查線程狀態(tài),當線程創(chuàng)建后或結(jié)束了,該狀態(tài)就不同于初始化狀態(tài)就會拋出IllegalThreadStateException異常。
測試代碼:
start不可以使用多次
/**
* @data 2019/11/8 - 下午11:57
* 描述:start不可以使用多次
*/
public class CantStartTwice {
public static void main(String[] args) {
Thread thread = new Thread();
thread.start();
thread.start();
}
}
4、注意點:
start方法是被synchronized修飾的方法,可以保證線程安全。
由jvm創(chuàng)建的main方法線程和system組線程,并不會通過start來啟動。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java數(shù)據(jù)結(jié)構(gòu)之散列表(動力節(jié)點Java學院整理)
散列表(Hash table,也叫哈希表),是根據(jù)關(guān)鍵字(key value)而直接進行訪問的數(shù)據(jù)結(jié)構(gòu)。這篇文章給大家介紹了java數(shù)據(jù)結(jié)構(gòu)之散列表,包括基本概念和散列函數(shù)相關(guān)知識,需要的的朋友參考下吧2017-04-04
java創(chuàng)建txt文件并寫入內(nèi)容的方法代碼示例
這篇文章主要介紹了java創(chuàng)建txt文件并寫入內(nèi)容的兩種方法,分別是使用java.io.FileWriter和BufferedWriter,以及使用Java7的java.nio.file包中的Files和Path類,需要的朋友可以參考下2025-01-01
idea運行java的配置詳細教程(包含maven,mysql下載配置)
程序員們在開發(fā)的時候,一定會用到Intellij?IDEA這個集成開發(fā)環(huán)境,這篇文章主要給大家介紹了關(guān)于idea運行java的配置(包含maven,mysql下載配置)的相關(guān)資料,需要的朋友可以參考下2024-05-05

