相比GCD NSOperation更加的灵活
1.NSInvocationOperation
创建操作 ---> 创建队列 ---> 操作加入队列
// 处理事务
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(handleInvocation:) object:@"hello"];
//如果没有创建队列直接启动事务就在主线程里
//[op start];
// 创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 操作加入队列
[queue addOperation:op];
//在这里不可以启动,因为已经启动,此时在去启动就会把一个在running状态的队列重新start 造成线程混乱直接GG
//可以用 [[NSOperationQueue mainQueue] addOperation:op];
//[op start];
2.NSBlockOperation
相比NSInvocationOperation,NSBlockOperation是函数式编程,代码可读性更强
//1:创建blockOperation
NSBlockOperation *bo = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
sleep(3);
}];
//1.1 添加执行代码块
[bo addExecutionBlock:^{
NSLog(@"这是一个执行代码块 - %@",[NSThread currentThread]);
}];
//1.2 设置监听
bo.completionBlock = ^{
NSLog(@"完成了!!!");
};
//2:创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//3:添加到队列
[queue addOperation:bo];
NSLog(@"事务添加进了NSOperationQueue");
3.优先级
- (void)demo{
// 优先级
NSBlockOperation *bo1 = [NSBlockOperation blockOperationWithBlock:^{
for (int i = 0; i < 10; i++) {
NSLog(@"**第一个操作** %d --- %@", i, [NSThread currentThread]);
}
}];
// 设置优先级 - 最高
bo1.qualityOfService = NSQualityOfServiceUserInteractive;
//创建第二个操作
NSBlockOperation *bo2 = [NSBlockOperation blockOperationWithBlock:^{
for (int i = 0; i < 10; i++) {
NSLog(@"第二个操作 %d --- %@", i, [NSThread currentThread]);
}
}];
// 设置优先级 - 最低
bo2.qualityOfService = NSQualityOfServiceBackground;
//2:创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//3:添加到队列
[queue addOperation:bo1];
[queue addOperation:bo2];
}
4.线程通讯
- (void)demo {
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.name = @"hello";
[queue addOperationWithBlock:^{
NSLog(@"%@ = %@",[NSOperationQueue currentQueue],[NSThread currentThread]);
//模拟请求网络
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(@"%@ --%@",[NSOperationQueue currentQueue],[NSThread currentThread]);
}];
}];
}
5.控制并发量
- (void)demo {
// 设置并发数
self.queue.name = @"hello";
self.queue.maxConcurrentOperationCount = 2;
for (int i = 0; i<10; i++) {
[self.queue addOperationWithBlock:^{ // 一个任务
[NSThread sleepForTimeInterval:2];
NSLog(@"%d-%@",i,[NSThread currentThread]);
}];
}
}
6.依赖关系
- (void)demo{
NSBlockOperation *bo1 = [NSBlockOperation blockOperationWithBlock:^{
[NSThread sleepForTimeInterval:0.5];
NSLog(@"请求token");
}];
NSBlockOperation *bo2 = [NSBlockOperation blockOperationWithBlock:^{
[NSThread sleepForTimeInterval:0.5];
NSLog(@"拿着token,请求数据1");
}];
NSBlockOperation *bo3 = [NSBlockOperation blockOperationWithBlock:^{
[NSThread sleepForTimeInterval:0.5];
NSLog(@"拿着数据1,请求数据2");
}];
// 建立依赖最容易犯的问题就是循环嵌套
[bo2 addDependency:bo1];
[bo3 addDependency:bo2];
//[bo1 addDependency:bo3];
[self.queue addOperations:@[bo1,bo2,bo3] waitUntilFinished:YES];
NSLog(@"执行完了?我要干其他事");
}
7.挂起、继续、取消
正在执行的操作无法挂起或者取消
执行结果发现,正在执行的操作无法取消,因为这要回想到之前的NSThread
只有在内部判断才能取消完毕
网友评论