C 多執行緒程式設計 使用Thread類建立執行緒

2022-03-19 18:55:34 字數 1070 閱讀 9959

使用thread類可以建立和控制線程。使用thread類需要引入系統的system.threading命名空間。

下面簡單示例

using system;

using system.collections.generic;

using system.linq;

using system.text;

using system.threading;

namespace threaddemo

, id: ",thread.currentthread.name, thread.currentthread.managedthreadid);

}static

void main(string args)

}}

這裡不能保證哪個結果顯輸出,執行緒由作業系統排程,每次哪個執行緒在前面是不同的。

使用thread類建立的執行緒預設的是前台執行緒,執行緒池中的執行緒總是後台執行緒。

前台執行緒在main方法結束後,還會執行,一直到所有前台執行緒都完成任務了,程式才會結束。

後台執行緒在main方法結束的時候,也會隨之一起結束。

後台執行緒非常適合完成後台任務。例如關閉word應用程式,拼寫檢查繼續執行其程序就沒有意義。這樣可以將這個程序設定為後台程序。

通過設定執行緒的isbackground屬性可以設定是否為後台程序。

using system;

using system.collections.generic;

using system.linq;

using system.text;

using system.threading;

namespace foregroundthread

static

void threadmain()

started", thread.currentthread.name);

thread.sleep(3000);

console.writeline("thread completed", thread.currentthread.name);}}

}

C 使用thread類進行多執行緒程式設計

c 11中引入了乙個用於多執行緒操作的thread類,簡單多執行緒示例 include include include using namespace std void thread01 void thread02 int main system pause 輸出 兩個子執行緒並行執行,join函式...

C 中的多執行緒使用 Thread 類

好文,現在c 已經建議擯棄使用 suspend,resume 暫停 恢復執行緒,也盡量少用 abort方法中斷乙個執行緒.建議使用執行緒的同步手段有 mutex manualresetevent autoresetevent,monitor.下面再對此進行詳細描述.thread類的建構函式有2類 一...

C 中的多執行緒使用 Thread 類

現在c 已經建議擯棄使用 suspend,resume 暫停 恢復執行緒,也盡量少用 abort方法中斷乙個執行緒.建議使用執行緒的同步手段有 mutex manualresetevent autoresetevent,monitor.下面再對此進行詳細描述.thread類的建構函式有2類 一種是不...