Java線程基礎

線程 是程序中的執行線程。Java 虛擬機允許應用程序併發地運行多個執行線程。

   每個線程都有一個優先級,高優先級線程的執行優先於低優先級線程。每個線程都可以或不可以標記爲一個守護程序。當某個線程中運行的代碼創建一個新 Thread 對象時,該新線程的初始優先級被設定爲創建線程的優先級,並且當且僅當創建線程是守護線程時,新線程纔是守護程序。

線程的ID是唯一標識getId()

線程的名稱:getName(),如果不設置線程名稱默認爲“Thread-xx”

線程的優先級:線程最小優先級爲1,最大爲10,默認爲5。

public final static int MIN_PRIORITY = 1;
    public final static int NORM_PRIORITY = 5;
    public final static int MAX_PRIORITY = 10;
可以通過set方法來設置線程的優先級

public final void setPriority(int newPriority) {
        ThreadGroup g;
        checkAccess();
        if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
            throw new IllegalArgumentException();
        }
        if((g = getThreadGroup()) != null) {
            if (newPriority > g.getMaxPriority()) {
                newPriority = g.getMaxPriority();
            }
            setPriority0(priority = newPriority);
        }
    }

   首先java中線程分守護線程和非守護線程(用戶線程),這兩種線程的區別可以看這篇博文,其次線程Thread類中有兩個嵌套類,一個是枚舉類State,還有一個是接口定義了線程的五種狀態還有一個是接口UncaughtExceptionHandler。Thread.State當 Thread 因未捕獲的異常而突然終止時,調用處理程序的接口。

線程的六種狀態:

    public enum State {
        /**
         * Thread state for a thread which has not yet started.
         */
        NEW,

        /**
         * Thread state for a runnable thread.  A thread in the runnable
         * state is executing in the Java virtual machine but it may
         * be waiting for other resources from the operating system
         * such as processor.
         */
        RUNNABLE,

        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * is waiting for a specified thread to terminate.
         */
        WAITING,

        /**
         * Thread state for a waiting thread with a specified waiting time.
         * A thread is in the timed waiting state due to calling one of
         * the following methods with a specified positive waiting time:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         */
        TIMED_WAITING,

        /**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         */
        TERMINATED;
    }
1、新建狀態(New):創建一個線程時,例如new Thread(r); 線程還沒有開始運行,此時線程處於新建狀態。
2、就緒狀態(Runnable):創建了線程,還需要調用線程的start()方法,線程纔會啓動,start方法創建線程運行的系統資源並調用run方法,當start方法返回之後線程就處於就緒狀態了。處於就緒狀態的線程並不一定立即運行run()方法,線程還必須同其他線程競爭CPU時間,只有獲得CPU時間纔可以運行線程。因爲在單CPU的計算機系統中,不可能同時運行多個線程,一個時刻僅有一個線程處於運行狀態。因此此時可能有多個線程處於就緒狀態。對多個處於就緒狀態的線程是由Java運行時系統的線程調度程序(thread scheduler)來調度的。
3、運行狀態(Running):當線程獲得CPU時間後,它才進入運行狀態,真正開始執行run()方法。
運行狀態的情況比較複雜
第一:線程如果執行run() main()方法結束後,完成邏輯,線程就進入Terminated


第二:當線程調用sleep()或者join()方法就會進入Blocked狀態,但是要注意的是阻塞的線程是不釋放當前所佔有的系統資源,當sleep()結束或者join()等待其他線程來到,當前線程則進入Runnable狀態等待JVM分配資源。


第三:當線程進入Runnable狀態,但是還沒有開始運行的時候,此時發現需要的資源處於同步狀態synchronized,這個時候線程將會進入Time waiting,JVM會使用隊列對這些線程進行控制,既先進行Time waiting的線程會先得到JVM資源進行執行進入Waiting


第四:如果處於Runnable的線程調用yield()讓出JVM資源,那麼就會進入New狀態和其他New狀態線程進行競爭重新進入Runnable


第五:如果當前線程調用wait()方法,則當前線程進入Time waiting但是這個時候當前線程會釋放所佔有的JVM資源,進入這個狀態過後是不能自動喚醒的,必須調用notify()或者notifyAll()方法,線程進入Waiting。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章