iOS开发中的并发、串行队列,同步、异步任务

来源:互联网 发布:numpy攻略 源码 编辑:程序博客网 时间:2024/04/30 03:37

在多线程开发中我们经常会遇到这些概念:并发队列、串行队列、同步任务、异步任务。我们将这四个概念进行组合会有四种结果:串行队列+同步任务、串行队列+异步任务、并发队列+同步任务、并发队列+异步任务。我们对这四种结果进行解释:

1.串行队列+同步任务:不会开启新的线程,任务逐步完成。

2.串行队列+异步任务:开启新的线程,任务逐步完成。

3.并发队列+同步任务:不会开启新的线程,任务逐步完成。

4.并发队列+异步任务:开启新的线程,任务同步完成。

我们如果要让任务在新的线程中完成,应该使用异步线程。为了提高效率,我们还应该将任务放在并发队列中。因此在开发中使用最多的是并发队列+异步任务。看代码:

// 串行队列+同步任务

- (void)serialSyn{

    dispatch_queue_t queue =dispatch_queue_create("serial",DISPATCH_QUEUE_SERIAL);

    dispatch_sync(queue, ^{

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

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

        }

    });

    dispatch_sync(queue, ^{

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

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

        }

    });

    dispatch_sync(queue, ^{

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

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

        }

    });

}

// 串行队列+异步任务

- (void)serialAsyn{

    dispatch_queue_t queue =dispatch_queue_create("serial",DISPATCH_QUEUE_SERIAL);

    dispatch_async(queue, ^{

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

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

        }

    });

    dispatch_async(queue, ^{

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

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

        }

    });

    dispatch_async(queue, ^{

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

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

        }

    });

}

// 并发队列+同步任务

- (void)concurrenSyn{

    dispatch_queue_t queue =dispatch_queue_create("concurrent",DISPATCH_QUEUE_CONCURRENT);

    dispatch_sync(queue, ^{

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

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

        }

    });

    dispatch_sync(queue, ^{

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

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

        }

    });

    dispatch_sync(queue, ^{

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

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

        }

    });

    

}

// 并发队列+异步任务

- (void)concurrentAsyn{

    dispatch_queue_t queue =dispatch_queue_create("concurrent",DISPATCH_QUEUE_SERIAL);

    dispatch_async(queue, ^{

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

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

        }

    });

    dispatch_async(queue, ^{

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

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

        }

    });

    dispatch_async(queue, ^{

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

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

        }

    });

}


看表格:



1 0
原创粉丝点击