開(kāi)啟多線程主要的三種方法NSThread、GCD、 NSOperation。
1.NSThread
1> 開(kāi)線程的幾種方式
先創(chuàng)建,后啟動(dòng)
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[thread start];
直接啟動(dòng)
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
[self performSelectorInBackground:@selector(run) withObject:nil];
2> 其他用法
NSThread *current = [NSThread currentThread]; //獲取當(dāng)前線程
+ (NSThread *)mainThread; // 獲得主線程
3> 線程間通信
performSelectorOnMainThread.....
2.GCD(重點(diǎn))
1.隊(duì)列的類(lèi)型
并發(fā)隊(duì)列
獲得全局的并發(fā)隊(duì)列: dispatch_get_global_queue串行隊(duì)列
a.自己創(chuàng)建 dispatch_queue_create
b.主隊(duì)列 dispatch_get_main_queue
2.執(zhí)行任務(wù)的方法類(lèi)型
- 同步(sync)執(zhí)行
- 異步(async)執(zhí)行
3.了解隊(duì)列和方法的配合使用
4.線程間通信
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 執(zhí)行耗時(shí)的異步操作...
dispatch_async(dispatch_get_main_queue(), ^{
// 回到主線程,執(zhí)行UI刷新操作
});
});
5.其他用法
dispatch_once //只執(zhí)行一次
dispatch_after //延遲執(zhí)行
dispatch_group_async\dispatch_group_notify
3.NSOperation
1. 基本使用
NSInvocationOperation
NSBlockOperation
2.NSOperationQueue(重點(diǎn))
- 最大并發(fā)數(shù)設(shè)置
- (void)setMaxConcurrentOperationCount:(NSInteger)cnt;
- 設(shè)置依賴
[operationB addDependency:operationA]; // 操作B依賴于操作A