- (void)test1 {
dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
printf("1");
sleep(1);
NSLog(@"1%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
printf("2");
sleep(1);
NSLog(@"2%@", [NSThread currentThread]);
});
dispatch_sync(queue, ^{
printf("3");
sleep(1);
NSLog(@"3%@", [NSThread currentThread]);
});
}
打印结果:

结果分析:因为是串行队列,遵循先进先出的原则,按照顺序执行。打印结果1、2、3。
关于线程分析,只要在新开辟的同步队列中执行dispatch_async就会开辟一个新的线程,同步方法又回到了主线程中打印。
- (void)test2 {
dispatch_queue_t myConcurrentQueue = dispatch_queue_create("com.gcd", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(myConcurrentQueue, ^{
NSLog(@"%d",1);
NSLog(@"1%@", [NSThread currentThread]);
});
dispatch_async(myConcurrentQueue, ^{
NSLog(@"%d",2);
NSLog(@"2%@", [NSThread currentThread]);
});
dispatch_sync(myConcurrentQueue, ^{
NSLog(@"%d",3);
NSLog(@"3%@", [NSThread currentThread]);
});
dispatch_async(myConcurrentQueue, ^{
NSLog(@"%d",4);
NSLog(@"4%@", [NSThread currentThread]);
});
}
打印结果:1234或者3124或者2314或者2134或者1324

分析:1、2都开辟了新的线程去打印,但是 3是在主线程打印的,所以无法保证哪个先执行。但是因为dispatch_sync会阻塞当前队列,所以 4 肯定是最后执行的,前3个数都是看cpu的。
- (void)test3 {
dispatch_queue_t queue = dispatch_queue_create("com.apple.com", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(actionTime:) userInfo:nil repeats:NO];
});
}
- (void) actionTime:(NSTimer *)timer
{
NSLog(@"-----%@",[NSDate date]);
}
结果:不会打印,因为开辟新的线程默认runloop是关闭的,所以不会打印。
网友评论