1. 程式人生 > 實用技巧 >執行緒和程序

執行緒和程序

2. 執行緒和程序

  • 程序:一個程式, QQ.exe Music.exe 程式的集合;
  • 一個程序往往可以包含多個執行緒,至少包含一個 !
  • Java預設有幾個執行緒? 2個mian、 GC
  • 執行緒:開了一個程序Typora ,寫字,自動儲存(執行緒負責的)
  • 對於Java而言: Thread、Runnable、 Callable
  • Java真的可以開啟執行緒嗎?開不了

Java呼叫本地方法start0由底層(C++)開啟

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();

        /* 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 {
            //呼叫本地方法
            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 */
            }
        }
    }
	//本地方法
    private native void start0();

併發、並行

併發(多執行緒操作同一個資源)

  • CPU一核,模擬出來多條執行緒,天下武功,唯快不破,快速交替並行(多個人-起行走)
  • CPU多核,多個執行緒可以同時執行;執行緒池
public static void main(String[] args) {
    //獲取CPU的核數
    System.out.println(Runtime.getRuntime().availableProcessors());
}

併發程式設計的本質:充分利用CPU的資源
所有的公司都很看重!
企業,掙錢=>提高效率,裁員,找一個厲害的人頂替三個不怎麼樣的人;
人員(減)、技術成本(高)

執行緒的6種狀態

wait/sleep區別

  1. 來自不同的類

    wait=>Object

    sleep=>Thread

  2. 是否會釋放鎖

    wait會釋放鎖,sleep不會

  3. 使用範圍不同

    wait必須在同步程式碼塊中,沒有鎖時使用會丟擲llegalMonitorStateException(正在等待的物件沒有鎖)

    sleep可以咋任意地方

視訊參考https://www.bilibili.com/video/BV1B7411L7tE
上一篇:什麼是JUC
下一篇:Lock鎖