多线程中并发数与挂起

1.设置最大并发数量:通过设置maxConcurrentOperationCount属性来设置,默认值是-1,不限制最大并发数量.

2.队列的挂起:设置属性suspended为YES,即可将队列挂起,也可以称为暂停

注意:

1).当前任务处于执行状态,设置队列挂起不会影响其执行,受影响的是那些还没有执行的任务

2).当队列设置为挂起状态后,可以通过修改其状态再次恢复任务

3.队列的取消

方法:-(void)cancelAllOperations,当取消任务后,任务不可恢复

注意:若任务操作时自定义NSOperation类型的话,执行完一个耗时操作后,需要加一是否取消任务的判断,再去执行另外一个耗时操作

-(void)main

{

    for (int i = 0; i < 5000; i++) {

        NSLog(@"--1--%@",[NSThread currentThread]);

    }

    if (self.cancelled) {

        return;

    }

    for (int i = 0; i < 5000; i++) {

        NSLog(@"--2--%@",[NSThread currentThread]);

    }

    if (self.cancelled) {

        return;

    }

    for (int i = 0; i < 5000; i++) {

        NSLog(@"--3--%@",[NSThread currentThread]);

    }

    if (self.cancelled) {

        return;

    }

    for (int i = 0; i < 5000; i++) {

        NSLog(@"--4--%@",[NSThread currentThread]);

    }

}

 

//最大并发数量

-(void)concurrentCount

{

    self.queue = [[NSOperationQueue alloc]init];

    self.queue.maxConcurrentOperationCount = 1;

    [self.queue addOperationWithBlock:^{

        for (int i = 0; i < 5000; i++) {

            NSLog(@"--1--%@",[NSThread currentThread]);

        }

    }];

    [self.queue addOperationWithBlock:^{

        for (int i = 0; i < 5000; i++) {

            NSLog(@"--2--%@",[NSThread currentThread]);

        }

    }];

    [self.queue addOperationWithBlock:^{

        for (int i = 0; i < 5000; i++) {

            NSLog(@"--3--%@",[NSThread currentThread]);

        }

    }];

    [self.queue addOperationWithBlock:^{

        for (int i = 0; i < 5000; i++) {

            NSLog(@"--4--%@",[NSThread currentThread]);

        }

    }];

 

}

//挂起与取消

-(void)suspendedAndCancel

{

    //挂起和恢复

    if (self.queue.suspended) {

        [self.queue setSuspended:NO];

    }else{

        [self.queue setSuspended:YES];

    }

    

    //取消

//    [self.queue cancelAllOperations];

}

 

转载于:https://www.cnblogs.com/PJXWang/p/5951837.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值