多執行緒基礎知識總結

2021-10-06 20:30:55 字數 2824 閱讀 3639

1. 什麼是執行緒:

/**

* 程式 程序 執行緒 協程

* 執行緒 : 簡單的說就是乙個程式裡面不同的執行路徑就是乙個執行緒

*/public class whatisthread catch (interruptedexception e) }}

}//當直接執行run方法不是由執行緒去排程的 因此是在同乙個main執行緒執行的

//當呼叫start方法的時候 是由執行緒去排程 因此和main執行緒是不同的兩個執行緒。

public static void main(string args) catch (interruptedexception e) }}

}

2. 怎麼去建立執行緒和執行緒的幾個常用方法

/**

* 怎麼去建立執行緒

*/public class howtocreatethread

3. 執行緒的狀態

public class threadstate  catch (interruptedexception e) }}

}public static void main(string args) catch (interruptedexception e)

system.out.println(mythread.getstate());

}}

3. synchronized關鍵字

public class t implements runnable

// public void m2()

// }

public static void main(string args)

}}

public class t2  catch (interruptedexception e) 

system.out.println(thread.currentthread().getname()+ " m1 end.");}}

public void m2() catch (interruptedexception e)

system.out.println(thread.currentthread().getname()+ " m2 end.");

}public static void main(string args) ).start();

new thread(()-> ).start();

}}

/**

* 模擬同步存在 非同步取錢的場景 因為同步方法不影響非同步的方法

*/public class t3 catch (interruptedexception e)

this.name = name;

this.balance = monery;

}private /*synchronized*/ double getmoney()

//乙個執行緒存錢 同時開啟兩個執行緒取錢

public static void main(string args) throws interruptedexception ).start();

new thread(()-> ).start();

new thread(()-> catch (interruptedexception e)

system.out.println(t3.getmoney());

}).start();

}}

synchronized基本概念

**

* synchronized 的底層實現 鎖的是物件不是方法

* 重量級鎖 jdk1.5大概 每次都會去找作業系統去請求資源 比較重。。

* 後來的改進。。鎖公升級的概念

* 偏向鎖:hotspot底層首先會記住當前執行緒的id 不會加鎖,下次再一次請求的時候發現是同乙個執行緒則會直接執行,意思就是偏向某乙個執行緒不加鎖

* 自旋鎖:當偏向鎖有其他執行緒徵用的時候會產生自旋鎖。開啟乙個新的執行緒while迴圈去等待資源 預設10次好像是。

* 超過次數公升級為重量級鎖。 自旋鎖只發生在使用者態cpu 不會去請求作業系統因此比較快

* * 擴充套件:執行時間長使用系統重量級鎖, 執行時間短使用自旋鎖。

執行緒數量多使用重量級鎖因此不需要額外消耗cpu, 執行緒數量少可以使用自旋鎖

*/public class t4

public synchronized void m2()

public static void main(string args)

}

volatile:

/**

* volatile 保證執行緒的可見性 禁止指令重排

* 執行緒可見性:在計算機中每個程式都是執行在自己的本地工作內容中的,同時計算機本身也有自己的主記憶體,

* 每個程式需要將主記憶體中的資訊拷貝乙份資料到本地記憶體之中,使用完畢之後再寫回給主記憶體。

* 指令重排:在正常的程式中程式一般都會去順序從上往下執行,但是編譯器有時候不會按照我們**寫的順序執行。

* 因此在執行過程中會出現順序的問題。 使用例子:單例模式

* */

public class volatilejichu

system.out.println("end...");

}public static void main(string args) throws interruptedexception

}

多執行緒基礎知識

建立乙個序列佇列,該佇列中從方的都是要依次執行的任務,dispatch queue serial 表示序列佇列的標示 dispatch queue t serialqueue dispatch queue create serial dispatch queue serial 建立乙個並行佇列,並行...

多執行緒 基礎知識

1 建立執行緒 extends thread implements runnable 啟動執行緒 threadl類的start 執行緒完成 1 run 方法執行完成 2 丟擲乙個未處理的異常導致執行緒的提前結束 2 執行緒的狀態 新建立 執行緒被建立,但是沒有呼叫start方法 可執行 runnab...

c 基礎知識 多執行緒

執行緒被定義為程式的執行路徑。每個執行緒都定義了乙個獨特的控制流。如果您的應用程式涉及到複雜的和耗時的操作,那麼設定不同的執行緒執行路徑往往是有益的,每個執行緒執行特定的工作。執行緒是輕量級程序。乙個使用執行緒的常見例項是現代作業系統中並行程式設計的實現。使用執行緒節省了 cpu 週期的浪費,同時提...