【发布时间】:2011-03-03 09:07:34
【问题描述】:
当我多次调用 performSelectorInBackground 时,作业会在同一个线程上排队吗?
所以第一个先执行,依此类推?
或者,它会在单独的线程中运行吗?
谢谢
【问题讨论】:
标签: iphone multithreading background
当我多次调用 performSelectorInBackground 时,作业会在同一个线程上排队吗?
所以第一个先执行,依此类推?
或者,它会在单独的线程中运行吗?
谢谢
【问题讨论】:
标签: iphone multithreading background
每次调用-performSelectorInBackground:withObject:都会创建一个新线程
Using NSObject to Spawn a Thread
In iOS and Mac OS X v10.5 and later, all objects have the ability to spawn a new thread and use it to execute one of their methods. The performSelectorInBackground:withObject: method creates a new detached thread and uses the specified method as the entry point for the new thread. For example, if you have some object (represented by the variable myObj) and that object has a method called doSomething that you want to run in a background thread, you could could use the following code to do that:
[myObj performSelectorInBackground:@selector(doSomething) withObject:nil];
The effect of calling this method is the same as if you called the detachNewThreadSelector:toTarget:withObject: method of NSThread with the current object, selector, and parameter object as parameters. The new thread is spawned immediately using the default configuration and begins running. Inside the selector, you must configure the thread just as you would any thread. For example, you would need to set up an autorelease pool (if you were not using garbage collection) and configure the thread’s run loop if you planned to use it. For information on how to configure new threads, see “Configuring Thread Attributes.”
【讨论】:
它们将同时执行,而不是一个接一个地执行, 试试这个有一个想法:
-(void)prova1{
for (int i = 1; i<=10000; i++) {
NSLog(@"prova UNO:%i", i);
}
}
-(void)prova2{
for (int i = 1; i<=10000; i++) {
NSLog(@"_________prova DUE:%i", i);
}
}
SEL mioMetodo = NSSelectorFromString(@"prova1");
[self performSelectorInBackground:mioMetodo withObject:nil];
SEL mioMetodo2 = NSSelectorFromString(@"prova2");
[self performSelectorInBackground:mioMetodo2 withObject:nil];
你会得到:
...
___prova DUE:795
prova UNO:798
___prova DUE:796
prova UNO:799
___prova DUE:797
prova UNO:800
___prova DUE:798
prova UNO:801
___prova DUE:799
prova UNO:802
___prova DUE:800
prova UNO:803
___prova DUE:801
...
如果您想要一个有 1 个方法的队列,请尝试将 2 个方法添加到 NSOperationQueue 并将其 setMaxConcurrentOperationCount 设置为 1...
【讨论】: