美文网首页
iOS 多线程-CGD

iOS 多线程-CGD

作者: 男人宫 | 来源:发表于2020-04-17 14:42 被阅读0次
  • 串行队列同步执行,不开启新线程,任务按顺序执行
 //串行队列,同步执行,不开启新线程,任务是按顺序执行的
    dispatch_queue_t queue = dispatch_queue_create("chuanxing1", DISPATCH_QUEUE_SERIAL);
    for (int i = 0; i < 10; i ++) {
        dispatch_sync(queue, ^{
            NSLog(@"hello---%d---%@",i,[NSThread currentThread]);
        });
    }
输出结果.png
  • 串行队列异步执行,会开启新线程(1个),任务按照顺序执行
//串行队列,异步执行,会启新线程(1个),任务是按顺序执行的
       dispatch_queue_t queue = dispatch_queue_create("chuanxing1", DISPATCH_QUEUE_SERIAL);
       for (int i = 0; i < 10; i ++) {
           dispatch_async(queue, ^{
               NSLog(@"hello---%d---%@",i,[NSThread currentThread]);
           });
       }
输出结果.png
  • 并行队列同步执行,不会开启新的线程,任务按照顺序执行
//并行队列,同步执行,不会启新线程,任务是按顺序执行的
    dispatch_queue_t queue = dispatch_queue_create("chuanxing1", DISPATCH_QUEUE_CONCURRENT);
    for (int i = 0; i < 10; i ++) {
        dispatch_sync(queue, ^{
            NSLog(@"hello---%d---%@",i,[NSThread currentThread]);
        });
    }

输出结果.png
  • 并行队列异步执行,会开启新的线程(多条),任务执行是无序的
//并行队列,同步执行,不会启新线程,任务是按顺序执行的
    dispatch_queue_t queue = dispatch_queue_create("chuanxing1", DISPATCH_QUEUE_CONCURRENT);
    for (int i = 0; i < 10; i ++) {
        dispatch_async(queue, ^{
            NSLog(@"hello---%d---%@",i,[NSThread currentThread]);
        });
    }
输出结果.png
  • 主队列异步执行.不会开启新线程,任务按顺序执行
//主队列异步执行.不会开启新线程,任务按顺序执行
    for (int i = 0; i < 10 ; i++) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"hello---%d---%@",i,[NSThread currentThread]);
        });
    }
输出结果.png
  • 主队列同步执行
    //会等着第一个人任务执行完成之后,才会继续往下执行,会造成死锁(ps:只要在主线程上会造成死锁)
for (int i = 0; i < 10 ; i++) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            NSLog(@"hello---%d---%@",i,[NSThread currentThread]);
        });
    }
输出结果

解决主线程同步造成的死锁问题

//解锁主线程同步造成的死锁
    for (int i = 0; i < 10 ; i++) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
               dispatch_sync(dispatch_get_main_queue(), ^{
                   NSLog(@"hello---%d---%@",i,[NSThread currentThread]);
               });
        });
    }
输出结果

相关文章

网友评论

      本文标题:iOS 多线程-CGD

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