1.NSOperation
对于NSOperation,In OS X v10.6 and later, operation queues ignore the value returned by this method and always start operations on a separate thread.就是一个operation就新建一个thread。但是,这个说法是针对 NSOperationQueue *testQueue = [[NSOperationQueue alloc] init]; 这种queue来说的,如果向mainQueue中加入operation,那么这些operation一定会执行在main thread中,而且他们会串行执行。
下面是关于mainQueue方法的一部分说明:
The returned queue executes one operation at a time on the app’s main thread.
下面看一段例子
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[mainQueue addOperationWithBlock:^{ for(int i=;i<;i++)
{
NSLog(@"i is %d",i);
} }]; [mainQueue addOperationWithBlock:^{ for(int m=;m<;m++)
{
NSLog(@"m is %d",m);
} }];
以下是它的部分输出
-- ::55.000 OperationQueueTest[:60b] i is
-- ::55.001 OperationQueueTest[:60b] i is
-- ::55.001 OperationQueueTest[:60b] i is
-- ::55.002 OperationQueueTest[:60b] i is
-- ::55.002 OperationQueueTest[:60b] i is
-- ::55.003 OperationQueueTest[:60b] i is
-- ::55.004 OperationQueueTest[:60b] m is
-- ::55.004 OperationQueueTest[:60b] m is
-- ::55.004 OperationQueueTest[:60b] m is
-- ::55.005 OperationQueueTest[:60b] m is
-- ::55.005 OperationQueueTest[:60b] m is
-- ::55.006 OperationQueueTest[:60b] m is
-- ::55.006 OperationQueueTest[:60b] m is
-- ::55.007 OperationQueueTest[:60b] m is
-- ::55.017 OperationQueueTest[:60b] m is
-- ::55.017 OperationQueueTest[:60b] m is
-- ::55.018 OperationQueueTest[:60b] m is
-- ::55.018 OperationQueueTest[:60b] m is
-- ::55.019 OperationQueueTest[:60b] m is
可以看出,加入mainQueue后,两个operation是顺序执行的。
再看下面一段代码
NSOperationQueue *testQueue = [[NSOperationQueue alloc] init];
[testQueue addOperationWithBlock:^{ NSLog(@"111111 thread is %@",[NSThread currentThread]);
for(int i=;i<;i++)
{
NSLog(@"i is %d",i);
} }]; [testQueue addOperationWithBlock:^{
NSLog(@"222222 thread is %@",[NSThread currentThread]);
for(int m=;m<;m++)
{
NSLog(@"m is %d",m);
} }];
下面是它的部分输出
-- ::59.566 OperationQueueTest[:] i is
-- ::59.566 OperationQueueTest[:] i is
-- ::59.564 OperationQueueTest[:] m is
-- ::59.566 OperationQueueTest[:] i is
-- ::59.566 OperationQueueTest[:] i is
-- ::59.567 OperationQueueTest[:] i is
-- ::59.567 OperationQueueTest[:] i is
-- ::59.568 OperationQueueTest[:] i is
-- ::59.568 OperationQueueTest[:] i is
-- ::59.568 OperationQueueTest[:] i is
-- ::59.569 OperationQueueTest[:] i is
-- ::59.569 OperationQueueTest[:] i is
-- ::59.567 OperationQueueTest[:] m is
-- ::59.570 OperationQueueTest[:] m is
-- ::59.569 OperationQueueTest[:] i is
-- ::59.571 OperationQueueTest[:] i is
-- ::59.572 OperationQueueTest[:] i is
-- ::59.571 OperationQueueTest[:] m is
-- ::59.573 OperationQueueTest[:] m is
-- ::59.573 OperationQueueTest[:] m is
-- ::59.574 OperationQueueTest[:] m is
-- ::59.575 OperationQueueTest[:] m is
-- ::59.575 OperationQueueTest[:] m is
-- ::59.576 OperationQueueTest[:] m is
-- ::59.577 OperationQueueTest[:] m is
可以看出Operation是同时在运行的,它们运行在2个不同的thread中!