使用NSOperation 与 NSOperationQueue实现多线程编程 的详解
1 先将需要执行的操作封装到一个NSOperation对象中
2 然后将NSOperation对象添加到NSOperationQueue中
3 系统会自动将NSOperation中封装的操作放到一条新线程中执行此过程你根本不需要考虑生命周期,同步,加锁问题等;
NSOperation步骤;
NSOperation并不具备封装操作的能力,必须使用它的子类,使用NSOperation子类的方式有3种:
1> NSInvocationOperation
2> NSBlockOperation
3> 自定义子类继承NSOperation,实现内部相应的方法
NSOperationQueue操作是可以把线程封装起来;不是同步是异步获取数据,也不需要考虑生命周期
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadOperation];
}
//把封装的线程数据添加到队列中
- (void)loadOperation
{
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"operation1%@",[NSThread currentThread]);
}];
NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"operation2%@",[NSThread currentThread]);
}];
// 一个NSOperation被添加到队列中会马上执行操作(异步执行)
//1 往2 中添加依赖 那么2 是提前执行
[operation1 addDependency:operation2];
[queue addOperation:operation1];
[queue addOperation:operation2];
}
//创建了异步线程
- (void)loadNSOperationQueue
{
//使用消息队列封装了线程
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
}];
[queue addOperationWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
}];
[queue addOperationWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
}];
[queue addOperationWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
}];
//同时只允许一条线程运行
[queue setMaxConcurrentOperationCount:1];
//取消queue中所有的操作
//[queue cancelAllOperations];
}
//创建了一条线程 方式一 同步的
- (void)loadInvocationOperation
{
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];
NSLog(@"operation%@" ,[NSThread currentThread]);
//执行完调用的;
operation.completionBlock = ^(){
NSLog(@"执行完毕");
};
//开启线程
[operation start];
}
//取消操作
//[operation cancel];
//创建了一条线程 方式一
- (void)loadBlockOperation
{
NSBlockOperation *block = [NSBlockOperation
blockOperationWithBlock:^(){
NSLog(@"执行第1次操作,线程:%@", [NSThread currentThread]);
}];
//封装数据操作
[block addExecutionBlock:^(){
NSLog(@"YOU执行第1次操作,线程:%@", [NSThread currentThread]);
}];
[block addExecutionBlock:^(){
NSLog(@"YOU执行第1次操作,线程:%@", [NSThread currentThread]);
}];
[block addExecutionBlock:^(){
NSLog(@"YOU执行第1次操作,线程:%@", [NSThread currentThread]);
}];
//开启线程
[block start];
}
- (void)run
{
NSLog(@"run%@",[NSThread currentThread]);
}