美文网首页
NSOperation 相关函数

NSOperation 相关函数

作者: xiaofu666 | 来源:发表于2021-09-06 15:47 被阅读0次
    - (void)testWithType:(NSInteger)type{
        for (int i=0; i<10; i++) {
            NSLog(@"operation%zd = %d - %@",type,i,[NSThread currentThread]);
        }
    }
    
    1. ** NSInvocationOperation**
        //默认是主线程  搭配NSOperationQueue实现多线程
        NSInvocationOperation *invocationOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(testWithType:) object:@(1)];
        [invocationOperation start];
    
    1. ** NSBlockOperation**
        //默认是主线程  搭配NSOperationQueue实现多线程
        NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
            for (int i=0; i<3; i++) {
                NSLog(@"主线程 = %d - %@",i,[NSThread currentThread]);
            }
        }];
        //添加任务会自动加入到多线程
        [blockOperation addExecutionBlock:^{
            for (int i=0; i<3; i++) {
                NSLog(@"可以实现多线程 = %d - %@",i,[NSThread currentThread]);
            }
        }];
        [blockOperation start];
    
    1. 线程依赖
        //线程依赖
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
            [self testWithType:1];//多线程
        }];
        NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
            [self testWithType:2];//多线程
        }];
        NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{
            [self testWithType:3];//多线程
        }];
        NSBlockOperation *operationAfter = [NSBlockOperation blockOperationWithBlock:^{
            for (int i=0; i<10; i++) {
                NSLog(@"operationAfter = %d - %@",i,[NSThread currentThread]);
            }
        }];
        [operationAfter addDependency:operation1];
        [operationAfter addDependency:operation2];
        [operationAfter addDependency:operation3];
        //operationAfter 依赖于 operation1,operation2,operation3
        [queue addOperation:operation1];
        [queue addOperation:operation2];
        [queue addOperation:operation3];
        [queue addOperation:operationAfter];
    
    1. 线程并发控制
        // 创建队列,默认并发
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        // 最大并发数:  =1为串行; >1为并行;
        queue.maxConcurrentOperationCount = 1;
        // 添加操作到队列
        [queue addOperationWithBlock:^{
            for (int i=0; i<10; i++) {
                NSLog(@"addOperationWithBlock1 = %d - %@",i,[NSThread currentThread]);
            }
        }];
        [queue addOperationWithBlock:^{
            for (int i=0; i<10; i++) {
                NSLog(@"addOperationWithBlock2 = %d - %@",i,[NSThread currentThread]);
            }
        }];
    ```[图片上传失败...(image-355539-1635760294185)]
    

    相关文章

      网友评论

          本文标题:NSOperation 相关函数

          本文链接:https://www.haomeiwen.com/subject/nyoewltx.html