C 多執行緒程式設計簡單例項

2021-06-22 12:38:25 字數 1224 閱讀 4845

using

system;

using system.collections;

using system.collections.generic;

using system.threading;

//////在開發中經常會遇到執行緒的例子,如果某個後台操作比較費時間,我們就可以啟動乙個執行緒去執行那個費時的操作,同時程式繼續執行。在某些情況下可能會出現多個執行緒的同步協同的問題,下面的例子就展示了在兩個執行緒之間如何協同工作。

//////

這個程式的思路是共同做一件事情(從乙個arraylist中刪除元素),如果執行完成了,兩個執行緒都停止執行。

//////

//////

public

class threaddemo

public threaddemo(

int number)

threadone = 

new thread(

new threadstart(run));

//兩個執行緒共同做一件事情

threadtwo = 

new thread(

new threadstart(run));

//兩個執行緒共同做一件事情

threadone.name = "執行緒1";

threadtwo.name = "執行緒2";

onnumberclear += 

new eventhandler(threaddemo_onnumberclear); }

//////開始工作

///

public

void action()

//////

共同做的工作

///

private

void run()

monitor.exit(

this);

//取消鎖定

thread.sleep(5); }}//

執行完成之後,停止所有執行緒

void threaddemo_onnumberclear(

object sender, eventargs e)

} 說明:要實現執行緒同步不止這一種方式。在這裡採用了事件,在事件處理程式裡中止了執行緒(主要是回答csdn論壇的乙個朋友的問題才用了這種辦法)。

多執行緒程式設計例項

1 建立乙個執行緒用createthread函式 引數1 指向security attribute結構體的乙個指標,再次可以設定為null,預設的安全性 引數2 指定初始提交的棧的大小,以位元組為單位。可以設定為0,使用預設大小。引數3 指向乙個lspthread start routing型別的應...

多執行緒程式設計例項

有四個執行緒1 2 3 4。執行緒 1的功能就是輸出 1,執行緒 2的功能就是輸出 2,以此類推 現在有四個檔案 abcd 初始都為空。現要讓四個檔案呈如下格式 a 1 2 3 4 1 2.b 2 3 4 1 2 3.c 3 4 1 2 3 4.d 4 1 2 3 4 1.程式 include in...

多執行緒程式設計例項

include include include include include using namespace std intgetsum vector int iterator first,vector int iterator last static string getcurrenttime ...