iOS GCD dispatch_sync 与dispatch_async 区别
dispatch_async(dispatch_get_main_queue(), ^{
sleep(4);
if ( [NSThread currentThread].isMainThread) {
NSLog(@"1同步");
}
else
{
NSLog(@"1异步");
}
});
dispatch_async(dispatch_get_main_queue(), ^{
sleep(4);
if ([NSThread currentThread].isMainThread) {
NSLog(@"2同步");
}
else
{
NSLog(@"2异步");
}
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
if ([NSThread currentThread].isMainThread) {
NSLog(@"3同步");
}
else
{
NSLog(@"3异步");
}
dispatch_async(dispatch_get_main_queue(), ^{
if ([NSThread currentThread].isMainThread) {
NSLog(@"4主线程同步");
}
else
{
NSLog(@"4异步");
}
});
});
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
sleep(4);
if ([NSThread currentThread].isMainThread)
{
NSLog(@"5同步");
}
else
{
NSLog(@"5异步");
}
});
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
sleep(4);
if ([NSThread currentThread].isMainThread)
{
NSLog(@"7同步");
}
else
{
NSLog(@"7异步");
}
});
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
sleep(4);
if ([NSThread currentThread].isMainThread)
{
NSLog(@"8同步");
}
else
{
NSLog(@"8异步");
}
});
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
sleep(4);
if ([NSThread currentThread].isMainThread)
{
NSLog(@"9同步");
}
else
{
NSLog(@"9异步");
}
});
dispatch_queue_t testQueue = dispatch_queue_create("testsync_gcd", DISPATCH_QUEUE_CONCURRENT);
dispatch_sync(testQueue, ^{
sleep(4);
if ([NSThread currentThread].isMainThread)
{
NSLog(@"6同步");
}
else
{
NSLog(@"6异步");
}
});
最终的执行顺序
2017-02-16 16:02:31.235 GCD[32197:890408] 3异步
2017-02-16 16:02:35.309 GCD[32197:890372] 5同步
2017-02-16 16:02:39.377 GCD[32197:890372] 7同步
2017-02-16 16:02:43.445 GCD[32197:890372] 8同步
2017-02-16 16:02:47.519 GCD[32197:890372] 9同步
2017-02-16 16:02:51.569 GCD[32197:890372] 6同步
2017-02-16 16:02:55.650 GCD[32197:890372] 1同步
2017-02-16 16:02:59.719 GCD[32197:890372] 2同步
2017-02-16 16:02:59.720 GCD[32197:890372] 4主线程同步