進程和線程html
說到多線程,必然繞不開進程與線程的概念及區別。編程
對於計算機而言,當前的操做系統能夠同時運行多個應用程序,而每個應用程序就是一個進程(Process),它擁有本身獨立的內存空間。線程是進程中的一個執行流程,是執行任務的最小單位。一個進程內部容許同時啓動多個線程(Thread),同時執行多個任務。線程是輕量級的進程,它負責在單個程序裏執行多任務,一般由操做系統負責多個線程的調度和執行。 多線程
/** * A thread state. A thread can be in one of the following states: * <ul> * <li>{@link #NEW} * A thread that has not yet started is in this state. * </li> * <li>{@link #RUNNABLE} * A thread executing in the Java virtual machine is in this state. *</li> * <li>{@link #BLOCKED} * A thread that is blocked waiting for a monitor lock * is in this state. * </li> * <li>{@link #WAITING} * A thread that is waiting indefinitely for another thread to * perform a particular action is in this state. * </li> * <li>{@link #TIMED_WAITING} * A thread that is waiting for another thread to perform an action * for up to a specified waiting time is in this state. * </li> * <li>{@link #TERMINATED} * A thread that has exited is in this state. * </li> * </ul> * * <p> * A thread can be in only one state at a given point in time. * These states are virtual machine states which do not reflect * any operating system thread states. * * @since 1.5 * @see #getState */ public static State toThreadState(int var0) { if ((var0 & 4) != 0) { return State.RUNNABLE; } else if ((var0 & 1024) != 0) { return State.BLOCKED; } else if ((var0 & 16) != 0) { return State.WAITING; } else if ((var0 & 32) != 0) { return State.TIMED_WAITING; } else if ((var0 & 2) != 0) { return State.TERMINATED; } else { return (var0 & 1) == 0 ? State.NEW : State.RUNNABLE; } }
線程狀態之間的轉換關係以下圖:併發
public Thread.State getState() { return VM.toThreadState(this.threadStatus); }
從源碼中能夠看出,線程的狀態與VM有很大的關係。在JVM中,與線程建立、運行、銷燬等關係比較大的是Java虛擬機棧內存。【JVM的基本機構可查看JVM之基本結構 】性能