/**
* 同步函数 + 主队列 = 卡住
*/
- (void)syncMain {
NSLog(@"syncMain-------begin");
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"1----%@", [NSThread currentThread]);
});
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"2----%@", [NSThread currentThread]);
});
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"3----%@", [NSThread currentThread]);
});
NSLog(@"syncMain-------end");
}
/**
* 异步函数 + 主队列 = 不开线程
* 主队列优先级高于异步函数,所以即使是异步函数,同样不创建线程
*/
- (void)asyncMain {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"1----%@", [NSThread currentThread]);
});
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"2----%@", [NSThread currentThread]);
});
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"3----%@", [NSThread currentThread]);
});
}
/**
* 异步函数 + 并发队列 = 开启多条线程,由于并发,会开启多条线程
*/
- (void)asyncConcurrent {
// 全局队列都是并发队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
for (NSInteger i = 0; i < 10; i++) {
NSLog(@"1----%@", [NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (NSInteger i = 0; i < 10; i++) {
NSLog(@"2----%@", [NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (NSInteger i = 0; i < 10; i++) {
NSLog(@"3----%@", [NSThread currentThread]);
}
});
}
/**
* 异步函数 + 串行队列 = 可以开启条线程,但是只会开一条
*/
- (void)asyncSerial {
dispatch_queue_t queue = dispatch_queue_create("com.guoqi.queue", NULL);
dispatch_async(queue, ^{
NSLog(@"1----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"2----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"3----%@", [NSThread currentThread]);
});
}
/**
* 同步函数 + 串行队列 = 不开线程,顺序执行
*/
- (void)syncSerial {
dispatch_queue_t queue = dispatch_queue_create("com.guoqi.queue", NULL);
dispatch_sync(queue, ^{
NSLog(@"1----%@", [NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"2----%@", [NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"3----%@", [NSThread currentThread]);
});
}
/**
* 同步函数 + 并发队列 = 不开线程,顺序执行
*/
- (void)syncConcurrent {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_sync(queue, ^{
NSLog(@"1----%@", [NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"2----%@", [NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"3----%@", [NSThread currentThread]);
});
}
网友评论