当我使用不同的任务在同一个队列上调用 dispatch_async 方法两次时,它会在不同的线程上执行任务,而不是在两个任务的同一线程上执行。
void(^myBlock)(void) = ^{
for(int i = 0;i < 10 ; i++)
{
NSLog(@"%d and current queue = %@",i,[NSThread currentThread]);
}
};
-(void)viewDidLoad
{
[super viewDidLoad];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_
DEFAULT, 0);
dispatch_async(queue,myBlock);
dispatch_async(queue,myBlock);
}
当我运行这个程序时,它会创建两个线程。以下是输出。
2013-09-10 17:45:20.435 ConcurrencyDemo[1331:30b] 0 和当前队列 = {name = (null), num = 3}
2013-09-10 17:45:20.435 ConcurrencyDemo[1331:1603] 0 和当前队列 = {name = (null), num = 2}
2013-09-10 17:45:20.438 ConcurrencyDemo[1331:1603] 1 和当前队列 = {name = (null), num = 2}
2013-09- 10 17:45:20.438 ConcurrencyDemo[1331:30b] 1 和当前队列 = {name = (null), num = 3}
2013-09-10 17:45:20.440 ConcurrencyDemo[1331:1603] 2 和当前队列 = { name = (null), num = 2}
2013-09-10 17:45:20.440 ConcurrencyDemo[1331:30b] 2 和当前队列 = {name = (null), num = 3}
2013-09-10 17:45 :20.441 ConcurrencyDemo[1331:1603] 3 和当前队列 = {name = (null), num = 2}
2013-09-10 17:45:20.441 ConcurrencyDemo[1331:30b] 3 和当前队列 = {name = (null), num = 3}
2013-09-10 17:45:20.442 ConcurrencyDemo[1331:30b] 4 和当前队列 = {name = (null), num = 3}
2013-09-10 17:45:20.442 ConcurrencyDemo[1331:1603] 4 和当前队列 = {name = (null), num = 2}
2013-09- 10 17:45:20.443 ConcurrencyDemo[1331:1603] 5 和当前队列 = {name = (null), num = 2}
2013-09-10 17:45:20.443 ConcurrencyDemo[1331:30b] 5 和当前队列 = { name = (null), num = 3}
2013-09-10 17:45:20.444 ConcurrencyDemo[1331:30b] 6 和当前队列 = {name = (null), num = 3}
2013-09-10 17:45 :20.444 ConcurrencyDemo[1331:1603] 6 和当前队列 = {name = (null), num = 2}
2013-09-10 17:45:20.445 ConcurrencyDemo[1331:30b] 7 和当前队列 = {name = (null), num = 3}
2013-09-10 17:45:20.445 ConcurrencyDemo[1331:1603] 7 和当前队列 = {name = (null), num = 2}
2013-09-10 17:45:20.446 ConcurrencyDemo[1331:1603] 8 和当前队列 = {name = (null), num = 2}
2013-09- 10 17:45:20.446 ConcurrencyDemo[1331:30b] 8 和当前队列 = {name = (null), num = 3}
2013-09-10 17:45:20.448 ConcurrencyDemo[1331:30b] 9 和当前队列 = { name = (null), num = 3}
2013-09-10 17:45:20.448 ConcurrencyDemo[1331:1603] 9 和当前队列 = {name = (null), num = 2}
谁能告诉我为什么会这样?