C 下用P2P技術實現點對點聊天

2021-06-20 21:20:13 字數 2189 閱讀 5761

**:

.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; 

// ****** 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(); 

} } 

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

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. 

C 下用P2P技術實現點對點聊天

p2p技術簡介 p2p,英文peer to peer的縮寫,中譯為對等互聯或點對點技術。p2p技術可以讓使用者可以直接連線到其他使用者的計算機,進行檔案共享與交換,同時p2p在深度搜尋 分布計算 協同工作等方面也大有用途。目前internet的儲存模式是 內容位於中心 而p2p技術的運用將使inte...

C 下用P2P技術實現點對點聊天

p2p技術簡介 理解p2p技術的最好方法莫過於仔細觀察並理解乙個實際的p2p應用程式。c 作為微軟.net戰略的重要棋子,對網路程式設計提供了很好的支援和優化。本文就通過乙個程式,向大家介紹一下c 下的p2p程式設計的方法和實現機理。本文的這個程式不是很有用,但卻很直觀地給出了p2p 點對點 程式設...

C 下用P2P技術實現點對點聊天

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