标签:
多线程的优点:
多线程的缺点:
使用NSOperation和NSOperationQueue实现多线程
注意:
NSInvocationOperation
NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(operationText) object:nil]; [operation start];
NSInvocationOperation创建的对象默认实在主线程中执行。
NSInvocationOperation *operation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(operationText) object:nil]; NSInvocationOperation *operation2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(operationText) object:nil]; NSOperationQueue *queue = [[NSOperationQueue alloc]init]; [queue addOperation:operation1]; [queue addOperation:operation2];
将操作放入队列中,在分线程中执行。
[queue setMaxConcurrentOperationCount:5];
队列以此可以最多执行的分线程。超出,则先执行完,在执行多余的。
NSBlockOperation
NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{ [NSThread sleepForTimeInterval:5]; NSLog(@"方法 :%d",[NSThread isMainThread]); }]; [operation2 start];
NSBlockOperation创建的对象默认是在主线程中执行的。
NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{ [NSThread sleepForTimeInterval:5]; NSLog(@"方法 :%d",[NSThread isMainThread]); }]; [operation2 addExecutionBlock:^{ [NSThread sleepForTimeInterval:5]; NSLog(@"方法1 :%d",[NSThread isMainThread]); }]; [operation2 start]
我们可以在block中添加其它任务,其它任务正常情况下是在分线程中执行。
NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"方法1 :%d",[NSThread isMainThread]); }]; NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"方法2 :%d",[NSThread isMainThread]); }]; NSOperationQueue *queue = [[NSOperationQueue alloc]init]; [queue addOperation:operation1]; [queue addOperation:operation2];
这样创建的方法都在分线程中执行。
自定义NSOperation对象
我们需要创建一个类,继承自NSOperation.
在类中实现-(void)main(){//实现的内容}
myOperation *operation1 = [[myOperation alloc]init]; myOperation *operation2 = [[myOperation alloc]init]; myOperation *operation3 = [[myOperation alloc]init]; NSOperationQueue *queue = [[NSOperationQueue alloc]init]; [queue addOperation:operation1]; [queue addOperation:operation2]; [queue addOperation:operation3];
我们可以设定操作对象的执行顺序。
[operation1 addDependency:operation2];
operation1依赖operation2,先执行operation2,再执行operation1
[operation3 setQueuePriority:NSOperationQueuePriorityHigh];
设置operation3的优先级
取消操作
[operation1 cancel];
取消某个操作。
[queue cancelAllOperations];
取消队列中的所有操作。
暂停操作
[queue setSuspended:YES]; [queue setSuspended:NO];
标签:
原文地址:http://www.cnblogs.com/wangyaoguo/p/4843846.html