ios多线程简记

先附上 block 链接:what fucking block syntax

NSOpration

    NSBlockOperation *opration1 = [NSBlockOperation blockOperationWithBlock:^{
        sleep(4);
        NSLog(@"下载二进制-----:%@",[NSThread currentThread]);
    }];
    
    NSBlockOperation *opration2 = [NSBlockOperation blockOperationWithBlock:^{
        sleep(2);
        NSLog(@"对二进制加密 ----:%@",[NSThread currentThread]);
    }];
    
    NSBlockOperation *opration3 = [NSBlockOperation blockOperationWithBlock:^{
        sleep(6);
        NSLog(@"发送加密二进制 ----:%@",[NSThread currentThread]);
    }];
//  添加任务的执行依赖关系
//    [opration3 addDependency:opration2];
//    [opration2 addDependency:opration1];
//  添加完成任务回调
//    [opration1 setCompletionBlock:^{NSLog(@"下载完成.....");}];
    NSOperationQueue * queue = [[NSOperationQueue alloc] init];
    //一次执行一个任务,sleep时间累加,否则同时执行。
    queue.maxConcurrentOperationCount = 1;
    [queue addOperations:@[opration1,opration2,opration3] waitUntilFinished:false];
    //要在queue之后写这句!!
    //[opration2 waitUntilFinished];
    //waitUntilFinished 当前线程(main)是否阻塞等待 queue所有任务|opration2 完成之后继续
    
    NSLog(@".................");

dispatch

  // 创建并发队列.
    dispatch_queue_t myqueue = dispatch_queue_create("myqueue", DISPATCH_QUEUE_CONCURRENT);
    // 创建串行队列
    dispatch_queue_t serQueue = dispatch_queue_create("serQueue", DISPATCH_QUEUE_SERIAL);
    
    // 创建三条任务.
    void(^task1)() = ^(void){
        for (int i = 0; i<3;i++) {
            NSLog(@"任务一一一 : %d   %@",i,[NSThread currentThread]);
        }
    };
    void(^task2)() = ^(void){
        for (int i = 0; i<3;i++) {
            NSLog(@"任务二二二 : %d   %@",i,[NSThread currentThread]);
        }
    };
    void(^task3)() = ^(void){
        for (int i = 0; i<3;i++) {
            NSLog(@"任务三三三 : %d   %@",i,[NSThread currentThread]);
        }
    };
    
    /** 异步不会阻塞当前线程,同步会阻塞当前线程。异步开启新线程。并发*/
     
    // 任务放到并发队列中异步执行。(顺序不可控,交替执行)
//    dispatch_async(myqueue,task1);
//    dispatch_async(myqueue,task2);
//    dispatch_async(myqueue,task3);
    
    
    // 并发队列-同步执行.(主线程,顺序执行)
//    dispatch_sync(myqueue, task2);
//    dispatch_sync(myqueue, task1);
//    dispatch_sync(myqueue, task3);
    
    
    // 串行队列 - 异步执行 (其他一条线程顺序执行)
//    dispatch_async(serQueue, task1);
//    dispatch_async(serQueue, task2);
//    dispatch_async(serQueue, task3);
    
    // 串行队列 - 同步执行 (主线程,顺序执行)
//    dispatch_sync(serQueue, task3);
//    dispatch_sync(serQueue, task1);
//    dispatch_sync(serQueue, task2);

转载于:https://my.oschina.net/dmxs/blog/1812644

你可能感兴趣的:(ios多线程简记)