1,pthread_create??
(unix自帶的線程創(chuàng)建, 不多說,都知道, 比較少用)
2,nsthread
優(yōu)點:NSThread 比其他兩個輕量級。
缺點:需要自己管理線程的生命周期,線程同步,線程同步時對數(shù)據(jù)的加鎖會有一定的系統(tǒng)開銷
兩種方式創(chuàng)建:
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument
[thread start]; //要手動去start開啟線程
+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument //會自動開啟線程
3,performSelectorInBackground:withObject: 來創(chuàng)建一個線程
[self performSelectorInBackground:@selector(run:) withObject:@"test"]; //在后臺運行某一個方法
其效果與 NSThread 的 detachNewThreadSelector:toTarget:withObject: 是一樣的。
4,nsoperation? (NSInvocationOperation 和 NSBlockOperation)
NSOperation是個抽象類,使用它必須用它的子類,可以實現(xiàn)它或者使用它定義好的兩個子類:NSInvocationOperation 和 NSBlockOperation。創(chuàng)建NSOperation子類的對象,把對象添加到NSOperationQueue隊列里執(zhí)行,我們會把我們的執(zhí)行操作放在NSOperation中main函數(shù)中。
nsoperation的子類要支持并發(fā)執(zhí)行的話并,需要重載如下4個方法(默認不是并發(fā)的)
//執(zhí)行任務(wù)主函數(shù),線程運行的入口函數(shù)
-(void)start
//是否允許并發(fā),返回YES,允許并發(fā),返回NO不允許。默認返回NO
-(BOOL)isConcurrent
- (BOOL)isExecuting
//是否已經(jīng)完成,這個必須要重載,不然放在放在NSOperationQueue里的NSOpertaion不能正常釋放。
(BOOL)isFinished
5,GCD
dispatch queue分為下面三種:1,Serial
又稱為private dispatch queues,同時只執(zhí)行一個任務(wù)。Serial queue通常用于同步訪問特定的資源或數(shù)據(jù)。當你創(chuàng)建多個Serial queue時,雖然它們各自是同步執(zhí)行的,但Serial queue與Serial queue之間是并發(fā)執(zhí)行的。
2,Concurrent
又稱為global dispatch queue,可以并發(fā)地執(zhí)行多個任務(wù),但是執(zhí)行完成的順序是隨機的。
3,Main dispatch queue
它是全局可用的serial queue,它是在應(yīng)用程序主線程上執(zhí)行任務(wù)的。
