我认为提出这个问题的最好方法是使用一些代码:
//Main method
for(int i = 0; i < 10; i++)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self foo:i];
});
}
- (void) foo: (int) i
{
@synchronized(self)
{
NSLog(@"%d",i);
}
}
在这种情况下,是否保证数字0-9会按顺序打印出来?是否有可能跳过正在运行队列中等待的线程之一?现实中又如何。实际上,这曾经发生过吗?如果我想要上面的行为(仍然使用线程)怎么办?我怎么能做到这一点?