進程的本質(zhì)是一個正在執(zhí)行的程序,,程序運行時系統(tǒng)會創(chuàng)建一個進程,并且給每個進程分配獨立的內(nèi)存地址空間保證每個進程地址不會相互干擾,。同時,,在 CPU 對進程做時間片的切換時,保證進程切換過程中仍然要從進程切換之前運行的位置出開始執(zhí)行,。所以進程通常還會包括程序計數(shù)器,、堆棧指針。
有時被稱為輕量級進程(Lightweight Process,,LWP),是程序執(zhí)行流的最小單元,。線程是程序中一個單一的順序控制流程,。進程內(nèi)一個相對獨立的、可調(diào)度的執(zhí)行單元,,是系統(tǒng)獨立調(diào)度和分派 CPU 的基本單位指運行中的程序的調(diào)度單位,。在單個程序中同時運行多個線程完成不同的工作,稱為多線程,。
進程有自己的獨立地址空間,每啟動一個進程,,系統(tǒng)就會為它分配地址空間,,建立數(shù)據(jù)表來維護代碼段、堆棧段和數(shù)據(jù)段,,這種操作非常昂貴,。而線程是共享進程中的數(shù)據(jù)的,使用相同的地址空間,,因此 CPU 切換一個線程的花費遠比進程要小很多,,同時創(chuàng)建一個線程的開銷也比進程要小很多,線程的上下文切換的性能消耗要小于進程,。
/** * start方法將導(dǎo)致this thread開始執(zhí)行,。由JVM調(diào)用this thread的run方法,。 * Causes this thread to begin execution; the Java Virtual Machine * calls the <code>run</code> method of this thread. * <p> * 結(jié)果是 調(diào)用start方法的當前線程 和 執(zhí)行run方法的另一個線程 同時運行。 * The result is that two threads are running concurrently: the * current thread (which returns from the call to the * <code>start</code> method) and the other thread (which executes its * <code>run</code> method). * <p> * 多次啟動線程永遠不合法,。 特別是,,線程一旦完成執(zhí)行就不會重新啟動。 * It is never legal to start a thread more than once. * In particular, a thread may not be restarted once it has completed * execution. * * @exception IllegalThreadStateException if the thread was already * started. * @see #run() * @see #stop() */ publicclassThreadimplementsRunnable{ /* Make sure registerNatives is the first thing <clinit> does. */ privatestaticnativevoidregisterNatives(); static { registerNatives(); } //start方法用synchronized修飾,,為同步方法 publicsynchronizedvoidstart(){ /** * 對于由VM創(chuàng)建/設(shè)置的main方法線程或“system”組線程,,不會調(diào)用此方法。 * 未來添加到此方法的任何新功能可能也必須添加到VM中,。 * 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. * status=0 代表是 status 是 "NEW",。 * A zero status value corresponds to state "NEW". */ if (threadStatus != 0) thrownew IllegalThreadStateException();
/* * 通知組該線程即將啟動,以便將其添加到線程組的列表中,,并且減少線程組的未啟動線程數(shù)遞減,。 * 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);
boolean started = false; try { //通知組該線程即將啟動,以便將其添加到線程組的列表中,,并且減少線程組的未啟動線程數(shù)遞減,。 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 */ } } } //native方法,JVM創(chuàng)建并啟動線程,,并調(diào)用run方法 privatenativevoidstart0();