多執行緒系列(二) 多執行緒基礎

2022-01-15 01:53:29 字數 3542 閱讀 8498

目錄

一、執行緒的幾種狀態

屬性:

方法:

執行緒的5個狀態:

1、建立狀態(new):對應 thread th= new thread(worker) 時 ,就建立了乙個新的執行緒,僅僅是新建狀態,程式還沒有執行執行緒中的**~

2、就緒狀態(runnable):對應 th.start()方法,新建執行緒在接收到start()命令之後,呼叫run()方法,具體的執行執行緒。

如果資源緊張,執行緒較多,有可能在切換到當前這個執行緒前,需要等待一段時間。當cpu切換到當前這個執行緒時,在給定的時間片內執行我們的執行緒。

3、執行狀態(running):在切換到當前執行緒時,在cpu給定的時間片內,真正的執行執行緒。

4、  阻塞狀態(blocked

):對應 join()、sleep()方法。阻塞狀態是當前執行執行緒,暫時中斷執行,讓出cup時間片,使得其他正在等待run()的執行緒可以真正run()。

<1> join()方法:將呼叫join()方法的執行緒,加入到當前執行緒。使得當前執行緒掛起,一直到呼叫join()方法執行緒執行完畢。 

static void main(string args)

static voidchildthread()

先顯示主線程的資訊,大約10s後,子執行緒資訊顯示,執行結果:

我們解開注釋:childthead.join(); 這裡需要理解的是,是將子執行緒childthead加入到主線程中,主線程掛起,直到子執行緒childthread執行完畢後,主線程才被喚醒,繼續執行。

我們想讓誰優先執行,就讓我們希望的執行緒呼叫join().所以以上執行的結果是,首先顯示子執行緒資訊,完畢後,主線程才顯示資訊。

thread.sleep(0);在我們遇到長時間執行的執行緒時,執行一下,會讓cpu根據優先順序對執行緒重新排隊選擇。也許會是當前這個執行緒,或許是優先順序更高的。

<3>suspend()這個方法不建議使用。

5、死亡狀態(dead):對應 abort()方法。讓執行緒進入死亡狀態有兩種方式:<1>程式結束後,執行緒自然就會結束。<2>執行中,丟擲異常。

abort(),就是讓執行緒丟擲異常來終止執行緒。

二、基礎執行緒

1、建立執行緒

常用有2種方式可以讓我們顯示建立乙個執行緒

public

thread(threadstart start);

public thread(parameterizedthreadstart start);

引數:threadstart(無參無返回值委託) 和 parameterizedthreadstart(有乙個引數無返回值委託)  就是乙個委託,如下:

public

delegate

void threadstart();

public

delegate

void parameterizedthreadstart(object obj);

先建立乙個與之(此例為:threadstart委託)對應的方法:

static

void

childthread()

再建立基礎執行緒:

system.threading.thread childthead = new

system.threading.thread(childthread);

childthead.start();

三、前台執行緒與後台執行緒clr將執行緒分為兩種,即前台執行緒和後台執行緒。

執行緒的狀態可以從前台和後台,在生命週期中來回切換。

應用程式主線程以及通過thread物件顯示建立的執行緒預設為前台執行緒,執行緒池的執行緒預設為後執行緒。

例項:

system.threading.thread backgroundthread = new

system.threading.thread(backgroundthreadworker);

if (!backgroundthread.isbackground)

backgroundthread.isbackground = true

; backgroundthread.start();

var mt =system.threading.thread.currentthread;

mt.name = "

main";

console.writeline(

"【main thread】: name—;isbackground—;threadstate—

", mt.name, mt.isbackground.tostring(), mt.threadstate.tostring());

console.writeline(

"main thread end.");

console.writeline();

//主線程沒有結束,後台執行緒繼續執行~~

與子執行緒委託對應的方法

public static voidbackgroundthreadworker()

;isbackground—;threadstate—", bc.name, bc.isbackground.tostring(), bc.threadstate.tostring());

system.threading.thread.sleep(10000);

console.writeline("background thread end.");

}

<1>我們執行以上程式,發現主線程(前台執行緒)的資訊顯示後,程式直接結束,後台執行緒也就結束,所以不顯示資訊。

<2>解開以下注釋,使得主線程在等待,所以大約10s後,子執行緒資訊顯示。

//主線程沒有結束,後台執行緒繼續執行~~

執行緒二 多執行緒基礎

任務量比較大,通過多執行緒可以提高效率時,需要非同步處理時,占用系統資源,造成阻塞的工作時,都可以採用多執行緒提高效率 執行緒建立 使用者執行緒和守護執行緒 j a分為兩種執行緒 使用者執行緒和守護執行緒 守護執行緒 在程式執行的時候在後台提供一種通用服務的執行緒,比如垃圾 執行緒就是乙個很稱職的守...

多執行緒基礎(二)

執行緒的優先順序 執行緒的優先順序有10個等級,分別用數字1 10表示 1是最低優先順序,10為最高,5為預設 理論上優先順序越高的執行緒獲取cpu時間片的次數就越多。執行緒是不能主動獲取cpu時間片的,只能被動的分配,通過調整優先順序可以最大程度改善獲取時間片的次數。interrupt方法 int...

C 多執行緒系列(二)

static void main string args thread.start console.readkey static void threadone string content static void main string args static void threadone obje...