iOS学习笔记-118.多线程17——NSOperationQueue队列的取消、暂停、恢复

来源:互联网 发布:豆瓣fm for mac打不开 编辑:程序博客网 时间:2024/06/05 08:19

  • 多线程17NSOperationQueue队列的取消暂停恢复
    • 一队列的取消暂停恢复
      • 1 暂停和恢复队列
      • 2 取消队列的所有操作
      • 3 取消和暂停必须是一个操作执行完了才起作用
      • 二代码示例
      • 三运行结果

多线程17——NSOperationQueue队列的取消、暂停、恢复

一、队列的取消、暂停、恢复

1.1 暂停和恢复队列

//暂停和恢复队列- (void)setSuspended:(BOOL)b; // YES代表暂停队列,NO代表恢复队列- (BOOL)isSuspended;

1.2 取消队列的所有操作

取消队列的所有操作,不可以恢复

- (void)cancelAllOperations;

==提示:也可以调用 NSOperation 的 - (void)cancel 方法取消单个操作==

1.3 取消和暂停必须是一个操作执行完了才起作用

取消和暂停必须是一个操作执行完了才起作用。比如说,我们执行5个操作,现在正在执行第2个操作,我们现在取消或者暂停是不会立即起作用的,直到操作2执行完了,才会起到作用。


二、代码示例

- (IBAction)startClick:(id)sender {    if(_queue==nil){        _queue = [[NSOperationQueue alloc]init];        _queue.maxConcurrentOperationCount = 1;    }    [self test1];}- (IBAction)suspendClick:(id)sender {    //暂停,是可以恢复    /*     队列中的任务也是有状态的:已经执行完毕的 | 正在执行 | 排队等待状态     */    //不能暂停当前正在处于执行状态的任务    [self.queue setSuspended:YES];}- (IBAction)goOnClick:(id)sender {    //继续执行    [self.queue setSuspended:NO];}- (IBAction)cancelClick:(id)sender {    //取消,不可以恢复    //该方法内部调用了所有操作的cancel方法    [self.queue cancelAllOperations];}-(void)test1{    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{        for (NSInteger i = 0; i<1000; i++) {            NSLog(@"1-%zd---%@",i,[NSThread currentThread]);        }    }];    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{        for (NSInteger i = 0; i<1000; i++) {            NSLog(@"2-%zd---%@",i,[NSThread currentThread]);        }    }];    NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{        for (NSInteger i = 0; i<1000; i++) {            NSLog(@"3-%zd---%@",i,[NSThread currentThread]);        }    }];    [self.queue addOperation:op1];    [self.queue addOperation:op2];    [self.queue addOperation:op3];}

三、运行结果

我们开始运行操作1的时候点击了暂停,它直到操作1执行完了才会暂停

[24039:119419] 1-0---<NSThread: 0x608000267c80>{number = 3, name = (null)}[24039:119419] 1-1---<NSThread: 0x608000267c80>{number = 3, name = (null)}[24039:119419] 1-2---<NSThread: 0x608000267c80>{number = 3, name = (null)}.....[24039:119419] 1-997---<NSThread: 0x608000267c80>{number = 3, name = (null)}[24039:119419] 1-998---<NSThread: 0x608000267c80>{number = 3, name = (null)}[24039:119419] 1-999---<NSThread: 0x608000267c80>{number = 3, name = (null)}
阅读全文
0 0