IOS 创建并发线程的实例详解
创建并发线程
主线程一般都是处理UI界面及用户交互的事儿的。其他的事一般就要另外的线程去处理,如下载,计算等。。。
现在先简单创建3个线程,分别打印出1-1000,,为了方便,线程3就放在主线程中执行。
- (void) firstCounter{
@autoreleasepool {
NSUInteger counter = 0;
for (counter = 0;
counter < 1000;
counter++){
NSLog(@"First Counter = %lu", (unsigned long)counter);
}
}
}
- (void) secondCounter{
@autoreleasepool {
NSUInteger counter = 0;
for (counter = 0;
counter < 1000;
counter++){
NSLog(@"Second Counter = %lu", (unsigned long)counter);
}
}
}
- (void) thirdCounter{
NSUInteger counter = 0;
for (counter = 0;
counter < 1000;
counter++){
NSLog(@"Third Counter = %lu", (unsigned long)counter);
}
}
- (void)viewDidLoad {
[super viewDidLoad];
[NSThread detachNewThreadSelector:@selector(firstCounter)
toTarget:self
withObject:nil];
[NSThread detachNewThreadSelector:@selector(secondCounter)
toTarget:self
withObject:nil];
/* Run this on the main thread */
[self thirdCounter];
}
由于thirdCounter 函数没有运行在单独的线程中,所以不需要自动释放池(autorelease pool)。这个方法将在应用程序的主线程中运行,每一个Cocoa Touch程序都会自
动的给该主线程创建一个自动释放池。
在代码的最后通过调用 detachNewThreadSelector,把将第一个计数器和第二个计数器运行在独立的线程中。现在,如果你运行程序,将会在控制台窗口看到如下信息:
Second Counter = 921
Third Counter = 301
Second Counter = 922
Second Counter = 923
Second Counter = 924
First Counter = 956
Second Counter = 925
Counter = 957
Second Counter = 926
First Counter = 958
Third Counter = 302
Second Counter = 927
Third Counter = 303
Second Counter = 928
可以看出,这三个计时器是同时运行的,他们输出的内容是随机交替的。 每一个线程必须创建一个 autorelease pool。在 autorelease pool 被 release 之前,autorelease pool 会一直持有被 autoreleased 的对象的引用。在引用计数内存管理环境中这是一个非常重要的机制,例如Cocoa Touch中的对象就能够被autoreleased。无论何时,在创建一个对象实例时,该对象的引用计数是1,但是当创建的autorelease pool对象被release了,那么 autorelease 的对象同样会发送一个 release 消息,如果此时,它的引用计数仍然是 1,那么该对象将被销毁。










