iOS多線程的方式
1.NSObject分類NSObject (NSThreadPerformAdditions)里自帶的
//手動創建NSThread
- (void)performSelector:(SEL)aSelector onThread:(NSThread*)thr withObject:(nullableid)arg waitUntilDone:(BOOL)wait modes:(nullableNSArray *)arrayNS_AVAILABLE(10_5,2_0);
- (void)performSelector:(SEL)aSelector onThread:(NSThread*)thr withObject:(nullableid)arg waitUntilDone:(BOOL)waitNS_AVAILABLE(10_5,2_0);
// equivalent to the first method with kCFRunLoopCommonModes
//自動創建一個NSThread
- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullableid)argNS_AVAILABLE(10_5,2_0);
2.NSThread
比較簡單,但是無法控制執行順序并發數量
NSThread*thread = [[NSThreadalloc]initWithTarget:selfselector:@selector(setImageViewImageWithInt:)object:url];
thread.threadPriority = index/10.0;
thread.name= [NSStringstringWithFormat:@"myThread%i",index];//設置線程名稱
[threadstart];
3.NSOperation
創建一個NSOperation對象(實際使用中創建NSInvocationOperation或者NSBlockOperation,推薦后者,方便),然后加入NSOperationQueue中執行
//NSInvocationOperation
NSInvocationOperation*operation = [[NSInvocationOperationalloc]initWithTarget:selfselector:@selector(setImageViewImageWithInt:)object:url];
[queueaddOperation:operation];
//NSBlockOperation
NSBlockOperation*blockOperation = [[NSBlockOperationalloc]init];
[blockOperationaddExecutionBlock:^{
[selfsetImageViewImageWithInt:url];
}];
[queueaddOperation:blockOperation];
- (void)addDependency:(NSOperation*)op;//設置依賴
- (void)removeDependency:(NSOperation*)op;//取消依賴
4.GCD
創建串行隊列
dispatch_queue_t queuet=dispatch_queue_create("creatQueue", DISPATCH_QUEUE_SERIAL);
創建并行隊列
dispatch_queue_t queuex=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
或者
dispatch_queue_tqueuex=dispatch_queue_create("creatQueue",DISPATCH_QUEUE_CONCURRENT);
異步執行
dispatch_async(queuex, ^{
});
同步執行
dispatch_sync(queuex, ^{
});
dispatch_apply():重復執行某個任務,但是注意這個方法沒有辦法異步執行(為了不阻塞線程可以使用dispatch_async()包裝一下再執行)。
dispatch_once():單次執行一個任務,此方法中的任務只會執行一次,重復調用也沒辦法重復執行(單例模式中常用此方法)。
dispatch_time():延遲一定的時間后執行。
dispatch_barrier_async():使用此方法創建的任務首先會查看隊列中有沒有別的任務要執行,如果有,則會等待已有任務執行完畢再執行;同時在此方法后添加的任務必須等待此方法中任務執行后才能執行。(利用這個方法可以控制執行順序,例如前面先加載最后一張圖片的需求就可以先使用這個方法將最后一張圖片加載的操作添加到隊列,然后調用dispatch_async()添加其他圖片加載任務)
dispatch_group_async():實現對任務分組管理,如果一組任務全部完成可以通過dispatch_group_notify()方法獲得完成通知(需要定義dispatch_group_t作為分組標識)。
5.線程同步
NSLock
[lock lock];
<#statements#>
[lock unlock];
@synchronized
@synchronized(token){
<statements>
}
dispatch_semaphore_t支持信號通知和信號等待
dispatch_semaphore_tt =dispatch_semaphore_create(1);
dispatch_semaphore_wait(t,DISPATCH_TIME_FOREVER);//等待-1
dispatch_semaphore_signal(t);//通知+1
NSCondition 控制線程通信
- (void)wait;//等待
- (BOOL)waitUntilDate:(NSDate*)limit;
- (void)signal;//喚醒一個線程
- (void)broadcast;//喚醒所有線程
參考:http://www.cnblogs.com/kenshincui/p/3983982.html#NSOperation