多线程-NSOperation的队列操作

为了演示NSOperation的队列操作,在视图上添加三个按钮,分别用来实现:
暂停 , 继续 和 取消操作

取消队列的所有操作
- (void)cancelAllOperations;
提示:也可以调用NSOperation的- (void)cancel方法取消单个操作
暂停和恢复队列
- (void)setSuspended:(BOOL)b; // YES代表暂停队列,NO代表恢复队列
- (BOOL)isSuspended;

"operationCount" 属性可以获取到当前队列中的操作数

多线程-NSOperation的队列操作_第1张图片
搭建UI.png

示例代码:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController{
    
    NSOperationQueue *_queue; // 全局队列
}

// 取消 : 只能够暂停还没执行的操作,正在执行的操作不能够暂停
- (IBAction)clickCancelButton:(id)sender {
    
    [_queue cancelAllOperations];// 取消所有操作
    NSLog(@"取消全部操作(队列操作数:%zd)",_queue.operationCount);
}

// 暂停 : 只能够暂停还没执行的操作,正在执行的操作不能够暂停
- (IBAction)clickSuspendButton:(id)sender {
    
    _queue.suspended = YES;// 暂停操作
    NSLog(@"操作暂停(队列操作数:%zd)",_queue.operationCount);
}

// 继续
- (IBAction)clickResumeButton:(id)sender {
    
    _queue.suspended = NO;// 继续操作
    NSLog(@"继续操作(队列操作数:%zd)",_queue.operationCount);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 实例化队列对象
    _queue = [[NSOperationQueue alloc] init];
    
    // 设置最大并发数 :同一时间执行的操作数目
    _queue.maxConcurrentOperationCount = 3;
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    // 通过for循环模拟20个操作
    for (int i = 0; i < 20; i ++) {
        
        // 异步执行操作
        [_queue addOperationWithBlock:^{
            
            [NSThread sleepForTimeInterval:3];
            NSLog(@"%d-->%@",i,[NSThread currentThread]);
        }];
    }
}

@end

结论:
"- (void)cancelAllOperations;" 方法与 "suspended"属性只能操控还没有被执行的操作,正在执行中的操作不能被取消或暂停

你可能感兴趣的:(多线程-NSOperation的队列操作)