C 中編寫多執行緒

2021-04-02 23:37:40 字數 2129 閱讀 6962

隨便看看!

.net將關於多執行緒的功能定義在system.threading名字空間中。因此,要使用多執行緒,必須先宣告引用此名字空間(using system.threading;)。

即使你沒有編寫多執行緒應用程式的經驗,也可能聽說過「啟動執行緒」「殺死執行緒」這些詞,其實除了這兩個外,涉及多執行緒方面的還有諸如「暫停執行緒」「優先順序」「掛起執行緒」「恢復執行緒」等等。下面將乙個乙個的解釋。

a.啟動執行緒

顧名思義,「啟動執行緒」就是新建並啟動乙個執行緒的意思,如下**可實現:

thread thread1 = new thread(new threadstart( count));

其中的 count 是將要被新執行緒執行的函式。

b.殺死執行緒

「殺死執行緒」就是將一線程斬草除根,為了不白費力氣,在殺死乙個執行緒前最好先判斷它是否還活著(通過 isalive 屬性),然後就可以呼叫 abort 方法來殺死此執行緒。

c.暫停執行緒

它的意思就是讓乙個正在執行的執行緒休眠一段時間。如 thread.sleep(1000); 就是讓執行緒休眠1秒鐘。

d.優先順序

這個用不著解釋了。thread類中有乙個threadpriority屬性,它用來設定優先順序,但不能保證作業系統會接受該優先順序。乙個執行緒的優先順序可 分為5種:normal, abovenormal, belownormal, highest, lowest。具體實現例子如下:

thread.priority = threadpriority.highest;

e.掛起執行緒

thread類的suspend方法用來掛起執行緒,知道呼叫resume,此執行緒才可以繼續執行。如果執行緒已經掛起,那就不會起作用。

if (thread.threadstate = threadstate.running)

f.恢復執行緒

用來恢復已經掛起的執行緒,以讓它繼續執行,如果執行緒沒掛起,也不會起作用。

if (thread.threadstate = threadstate.suspended)

下面將列出乙個例子,以說明簡單的執行緒處理功能。此例子來自於幫助文件。

using system;

using system.threading;

此**產生的輸出類似如下內容:

main thread: start a second thread.

main thread: do some work.

threadproc: 0

main thread: do some work.

threadproc: 1

main thread: do some work.

threadproc: 2

main thread: do some work.

threadproc: 3

main thread: call join(), to wait until threadproc ends.

threadproc: 4

threadproc: 5

threadproc: 6

threadproc: 7

threadproc: 8

threadproc: 9

main thread: threadproc.join has returned.  press enter to end program.

// ****** threading scenario:  start a static method running

// on a second thread.

public class threadexample ", i);

// yield the rest of the time slice.

thread.sleep(0);}}

public static void main()

console.writeline("main thread: call join(), to wait until threadproc ends.");

t.join();

console.writeline("main thread: threadproc.join has returned.  press enter to end program.");

console.readline();}}

C 中編寫多執行緒

在c 中早都聽說這個東西了,但是以前一直沒有使用過,現在第一次嘗試,來衝衝電。net將關於多執行緒的功能定義在system.threading名字空間中。因此,要使用多執行緒,必須先宣告引用此名字空間 using system.threading 即使你沒有編寫多執行緒應用程式的經驗,也可能聽說過 ...

C 中編寫多執行緒 1

net將關於多執行緒的功能定義在system.threading名字空間中。因此,要使用多執行緒,必須先宣告引用此名字空間 using system.threading 即使你沒有編寫多執行緒應用程式的經驗,也可能聽說過 啟動執行緒 殺死執行緒 這些詞,其實除了這兩個外,涉及多執行緒方面的還有諸如 ...

在C 中編寫多執行緒應用程式

以前在使用vb來實現多執行緒的時候,發現有一定的難度。雖然也有這樣那樣的方法,但都不盡人意,但在c 中,要編寫多執行緒應用程式卻相當的簡單。這篇文章將作簡要的介紹,以起到拋磚引玉的作用!net將關於多執行緒的功能定義在system.threading名字空間中。因此,要使用多執行緒,必須先宣告引用此...