https://www.jianshu.com/p/0b0d9b1f1f19web
線程同步、 延時執行、 單例模式多線程
1、Pthreads:併發
POSIX線程異步
pthread_create(&thread, NULL, start, NULL);async
2、NSThreadspa
1—先建立線程類,再啓動線程
// 建立3d
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:nil];orm
// 啓動隊列
[thread start];
2-建立並自動啓動
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:nil];
3-NSObject 的方法建立並自動啓動
[self performSelectorInBackground:@selector(run:) withObject:nil];
3、GCD
任務 和 隊列
同步(sync) 和 異步(async)
會不會阻塞當前線程,直到 Block 中的任務執行完畢!
串行隊列 和 並行隊列
異步:
串行隊列:開多個線程,單個執行
並行隊列:開不少線程,一塊兒執行
主隊列-串行
dispatch_queue_t queue = dispatch_get_main_queue();
本身建立的隊列
DISPATCH_QUEUE_SERIAL 或 NULL 表示建立串行隊列。傳入 DISPATCH_QUEUE_CONCURRENT 表示建立並行隊列。
全局並行隊列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
同步任務
dispatch_sync
異步任務
dispatch_async
隊列組
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_async(group, queue, ^{
dispatch_group_async(group, dispatch_get_main_queue(), ^{
dispatch_group_async(group, queue, ^{
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
??闌珊用法:dispatch_barrier_async
4、NSOperation和NSOperationQueue
NSInvocationOperation 和 NSBlockOperation + start
addExecutionBlock
Operation 添加多個執行 Block,任務 會併發執行,在主線程和其它的多個線程 執行這些任務
自定義Operation
main()
NSOperationQueue
主隊列
NSOperationQueue *queue = [NSOperationQueue mainQueue];
其餘隊列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[operation addExecutionBlock:
[queue addOperation:operation];
maxConcurrentOperationCount = 1 串行隊列
添加依賴
[operation2 addDependency:operation1]; //任務二依賴任務一
[operation3 addDependency:operation2]; //任務三依賴任務二
[queue addOperations:@[operation3, operation2, operation1] waitUntilFinished:NO];
removeDependency 來解除依賴關係。
線程同步
互斥鎖 :
@synchronized(self)
/須要執行的代碼塊
NSLock
NSRecursiveLock 嵌套鎖
同步執行
1、dispatch_sync
2、
[queue addOperation:operation];
[operation waitUntilFinished];
延遲執行
1-
[self performSelector:@selector(run:) withObject:@"abc" afterDelay:3];
2-
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), queue, ^{
3-
從其餘線程回到主線程的方法
1、[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:NO];
2、GCD
//Objective-C
dispatch_async(dispatch_get_main_queue(), ^{
});
3、NSOperationQueue
//Objective-C
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
}];