網(wǎng)路基礎(chǔ)篇-多線程

開(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
3. 自定義Operation(了解基本流程)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容