iOS中多线程的总结

2018-11-17  本文已影响4人  开着保时捷堵你家门口

@synchronized(锁对象){//需要锁定的代码}

线程间的通讯

[selfperformSelectorOnMainThread:@selector(<#selector#>) withObject:<#(nullable id)#> waitUntilDone:<#(BOOL)#>];

    [selfperformSelector:<#(nonnull SEL)#> onThread:<#(nonnull NSThread *)#> withObject:<#(nullable id)#> waitUntilDone:<#(BOOL)#>]

串行队列

             dispatch_queue_tqueue =dispatch_queue_create("wangjianye",NULL)

dispatch_queue_tqueue =dispatch_get_main_queue()     主队列

并发队列

dispatch_queue_tqueue =dispatch_get_global_queue(DISPATCH_TARGET_QUEUE_DEFAULT,0 )

同步函数

                dispatch_sync(queue, ^{

                    })

异步函数

                dispatch_async(queue, ^{

                    })

队列组

 dispatch_group_tgroup =dispatch_group_create();

   dispatch_group_async(group,queue, ^{

    })

   dispatch_group_async(group,queue, ^{

    })

   dispatch_group_notify(group, main_queue, ^{

    })

NSOperation和NSOperationQueue实现多线程的具体步骤

(1)先将执行的操作封装到NSOperation对象中

(2)然后将NSOperation对象添加到NSOperationQueue中

(3)系统会自动将NSOperation封装的操作放到一个新的线程中执行

NSOperation是个抽象类,并不具备封装操作的能力,必须使⽤它的子类

使用NSOperation⼦类的方式有3种:

(1)NSInvocationOperation

(2)NSBlockOperation

(3)自定义子类继承NSOperation,实现内部相应的⽅法

NSInvocationOperation的用法:

NSInvocationOperation*operation = [[NSInvocationOperationalloc]initWithTarget:selfselector:@selector(run)object:nil];

    [operationstart];

NSBlockOperation的用法:

 NSBlockOperation*operation = [NSBlockOperationblockOperationWithBlock:^{

    }];

添加执行, 加不加都可以:

[operationaddExecutionBlock:^{

    }];

[operationaddExecutionBlock:^{

    }];

    [operationstart];

NSOperationQueue的用法:

NSOperationQueue*queue = [[NSOperationQueuealloc]init];

    [queue addOperation:operation0];

    [queue addOperation:operation1];

    [queue addOperation:operation2];

    [queueaddOperationWithBlock:^{

    }];

队列的取消操作:

[queuecancelAllOperations]

暂停与恢复队列:

 [queuesetSuspended:YES]

设置NSOperation 在queue的优先级

[operationsetQueuePriority:NSOperationQueuePriorityNormal]

设置 NSOperation 的依赖

[operationaddDependency:operation1]

设置NSOperation 的完成

[operationsetCompletionBlock:^{

    }];

自定义NSOperation的子类

上一篇下一篇

猜你喜欢

热点阅读