C 培訓2019 10 11多執行緒 執行緒等待

2021-09-28 12:55:38 字數 2168 閱讀 7513

考慮到多執行緒是因為在做漢內塔動畫時,當移動的數量變多或者移動時間比較長時,會出現窗體卡死的現象,直到移動結束才會顯示出來。

查資料發現與執行緒有關(或者說多執行緒可以解決)。

1、執行緒建立

//建立執行緒

thread thread =

newthread

(//注意這裡直接填入方法,其實是省略了。

//裡面實際接受的是委託的例項,微軟允許省略例項化直接寫方法名。類似的情況有「+=」註冊後面。

//這裡不省略可以替換為:

//threadstart threadstart = new threadstart( function );

//thread thread = new thread( threadstart );

//啟動執行緒

thread.

start()

;//強制關閉執行緒

thread.

abort()

;

2、需要傳值進入執行緒的方法時

例如:子執行緒呼叫的方法為void addnumber (int na , int nb)

提供一種方法

申明時使用parameterizedthreadstart,如下

thread thread =

newthread

(new

parameterizedthreadstart

( animatemovement )

);

這樣呼叫時候,可以用

int y=10;

int[

] xyarray =

newint

; thread.

start

( xyarray )

;

定義方法時,傳入為object型別

void addnumber (

object coord)

void form1_load( object sender, eventargs e )下加入以下**,也就是不檢查是否跨執行緒呼叫窗體

// other thread can control forms

control.checkforillegalcrossthreadcalls =

false

;

4、當要等待子執行緒執行完畢,才繼續執行主線程時。

首先在方法體外定義乙個 lock

object locker =

newobject()

;

然後在呼叫子執行緒的start( )方法後加入如下**:

其中finishcount表示子執行緒執行次數,會寫在子執行緒執行的方法最後;

_threadcount表示主線程要等待幾次子執行緒

lock

(locker)

}

最後在子執行緒的方法中最後加入:

lock

(locker)

注意:若要多次呼叫,則需要將finishcount清零。

完整**如下:

using system.threading;

namespace threadstudy

lock

(locker)

} console.

writeline

("thread finished!");

}private

void

threadmethod

(object obj)

", obj.

tostring()

);lock

(locker)}}

}

4、執行緒被終止(abort())了無法再次啟動(start()
可以先掛起suspend,再resume()

python2執行緒 python多執行緒2執行緒應用

上 1 經典的生產者,消費者問題 2 lock和rlock差不多 lock會死鎖,rlock不會,具體google coding gbk created on 2013 1 4 author jimmy note 1 乙個簡單的建立執行緒例子,外加生產者消費者問題 2 執行緒同步初步 import ...

c 執行緒池 多執行緒

1。設定引數類 using system using system.collections.generic using system.text public class stateinfo 執行緒開啟方法類 using system using system.collections.generic ...

C 多執行緒 建立執行緒

c 中線程的建立一般是通過std thread類實現的,具體的實現方式有以下幾種 void operator int a 過載括號運算子。如果無參則為void operator 這裡有兩種方法通過成員函式建立。而這兩種方法恰好也就是靜態成員函式和非靜態成員函式的區別。靜態成員函式與物件無關,只屬於類...