前言
首先比較一下NSTread 和GCD浩考,NSOperation三者之間的優(yōu)缺點:
NSThread:
NSThread 比其他兩個輕量級,使用簡單叉谜。但是需要自己管理線程的生命周期貌嫡、線程同步、加鎖檀咙、休眠以及喚醒等。線程同步對數(shù)據(jù)的加鎖會有一定的系統(tǒng)開銷璃诀,因此不建議用來管理線程弧可,可以作為簡單的開啟新線程的操作。NSOperation:
NSOperation是基于GCD封裝劣欢,面向?qū)ο蟮淖厮小2恍枰P(guān)心線程管理,數(shù)據(jù)同步的事情凿将,控制并發(fā)數(shù)校套,可以把精力放在自己需要執(zhí)行的操作上。GCD:
GCD是基于C語言的牧抵,可替代NSThread笛匙, NSOperation的高效和強(qiáng)大的技術(shù),在多線程的管理和運用上使用起來非常的靈活犀变,不僅對線程的管理妹孙,和復(fù)雜線程的需求都能派上用場。
NSTread的使用
線程基本創(chuàng)建
1.
// 初始化線程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(timeSel) object:nil];
// 設(shè)置線程的優(yōu)先級(0.0 - 1.0获枝,1.0最高級)
thread.threadPriority = 1;
// 開啟線程
[thread start];
// 另一種新建線程蠢正,調(diào)用@selector方法
[NSThread detachNewThreadSelector:@selector(timeSel) toTarget:self withObject:nil];
// 獲取當(dāng)前線程
NSThread *currentThread = [NSThread currentThread];
// 獲取主線程
NSThread *mainThread = [NSThread mainThread];
// 暫停7s
[NSThread sleepForTimeInterval:7];
// 或者
NSDate *dateTime = [NSDate dateWithTimeInterval:7 sinceDate:[NSDate date]];
[NSThread sleepUntilDate:dateTime]; //睡眠,直到時間dateTime線程繼續(xù)進(jìn)行操作
線程間通訊省店,常用方法performSelector
:
//在當(dāng)前線程嚣崭。延遲執(zhí)行。
[self performSelector:@selector(test) withObject:nil afterDelay:1];
// 回到主線程懦傍。
// waitUntilDone(阻塞當(dāng)前的線程):如果為YES雹舀,就必須等回調(diào)方法執(zhí)行完成之后才能執(zhí)行后面的代碼;
// 如果是NO:就是不等回調(diào)方法結(jié)束谎脯,不會阻塞當(dāng)前線程
[self performSelectorOnMainThread:@selector(test) withObject:nil waitUntilDone:YES];
//開辟子線程
[self performSelectorInBackground:@selector(test) withObject:nil];
//在指定線程執(zhí)行
[self performSelector:@selector(test) onThread:[NSThread currentThread] withObject:nil waitUntilDone:YES]
需要注意的是:如果是帶afterDelay的延時函數(shù)葱跋,會在內(nèi)部創(chuàng)建一個 NSTimer持寄,然后添加到當(dāng)前線程的Runloop中源梭。也就是如果當(dāng)前線程沒有開啟runloop娱俺,該方法會失效。在子線程中废麻,需要啟動runloop(注意調(diào)用順序)
[self performSelector:@selector(test) withObject:nil afterDelay:1];
[[NSRunLoop currentRunLoop] run];