多线程GCD 队列 异步 网络 socket block 循环引用多线程iOS Developer

GCD队列

2016-07-27  本文已影响94人  CaesarsTesla

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self syncConcurrent];
}

 -(void)syncMain{
    //1、获得主队列
dispatch_queue_t queue = dispatch_get_main_queue();
NSLog(@"%s",__func__);
    //2、将任务加进队列
dispatch_sync(queue, ^{
    NSLog(@"1----%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
    NSLog(@"2----%@",[NSThread currentThread]);
});
/*2016-07-27 22:03:18.257 GCD[1474:205778] -[ViewController syncMain]*/
}
-(void)asyncMain{
//1、获得主队列
dispatch_queue_t queue = dispatch_get_main_queue();
//2、将任务添加进队列
dispatch_async(queue, ^{
    NSLog(@"1----%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
    NSLog(@"2----%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
    NSLog(@"3----%@",[NSThread currentThread]);
});
/*
 2016-07-27 22:01:12.524 GCD[1461:204697] 1----<NSThread: 0x7fe0d0606430>{number = 1, name = main}
 2016-07-27 22:01:12.525 GCD[1461:204697] 2----<NSThread: 0x7fe0d0606430>{number = 1, name = main}
 2016-07-27 22:01:12.526 GCD[1461:204697] 3----<NSThread: 0x7fe0d0606430>{number = 1, name = main}
 */
}
-(void)syncSerial{
//1、获得串行队列
dispatch_queue_t queue = dispatch_queue_create("com.mudy.queue", DISPATCH_QUEUE_SERIAL);
//2、将任务添加到队列中
dispatch_sync(queue, ^{
     NSLog(@"1----%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
    NSLog(@"2----%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
    NSLog(@"3----%@",[NSThread currentThread]);
});
/*
 2016-07-27 22:09:31.890 GCD[1509:209789] 1----<NSThread: 0x7fcb3b506770>{number = 1, name = main}
 2016-07-27 22:09:31.891 GCD[1509:209789] 2----<NSThread: 0x7fcb3b506770>{number = 1, name = main}
 2016-07-27 22:09:31.892 GCD[1509:209789] 3----<NSThread: 0x7fcb3b506770>{number = 1, name = main}
 */
}
-(void)syncConcurrent{
dispatch_queue_t queue = dispatch_queue_create("com.mudy.queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_sync(queue, ^{
    NSLog(@"1-------%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
    NSLog(@"2-------%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
    NSLog(@"3-------%@",[NSThread currentThread]);
});
/*
 2016-07-27 22:20:11.875 GCD[1560:215430] 1-------<NSThread: 0x7f9d3af02e70>{number = 1, name = main}
 2016-07-27 22:20:11.877 GCD[1560:215430] 2-------<NSThread: 0x7f9d3af02e70>{number = 1, name = main}
 2016-07-27 22:20:11.878 GCD[1560:215430] 3-------<NSThread: 0x7f9d3af02e70>{number = 1, name = main}
 */
}
并发队列 手动创建的串行队列 主队列
同步 没有开启新线程 串行执行任务 没有开启新线程 串行执行任务 没有开启新线程 串行执行任务
异步 有开启新线程 并发执行任务 有开启新线程 串行执行任务 没有开启新线程 串行执行任务
上一篇下一篇

猜你喜欢

热点阅读