創(chuàng)建線程:
for (int i = 0; i < 1000000; ++i) {
//總結(jié):test At: xcode8,ios 9.3.4
//1,當(dāng)用CFRunLoopRun(),然后調(diào)用CFRunLoopStop禁荒,此方法是后果會輸出current thread帅刊,thread dealloc躬窜,current thread毅整,thread dealloc ...所以不會用內(nèi)存問題
//2,當(dāng)用 [runLoop run];,然后調(diào)用CFRunLoopStop,此方法會current thread,current thread裆赵,... 最后輸出[NSThread start]: Thread creation failed with error 35.然后app卡住阳谍,然后app crash. 內(nèi)存不會暴增。但是線程無法銷毀
//3,當(dāng)用 [runLoop runMode:NSRunLoopCommonModes beforeDate:[NSDate distantFuture]];,然后調(diào)用CFRunLoopStop,此方法會佣耐。[ViewController performSelector:onThread:withObject:waitUntilDone:modes:]: target thread exited while waiting for the perform' crash。是因?yàn)?[runLoop runMode:NSRunLoopCommonModes beforeDate:[NSDate distantFuture]]; 無法阻塞線程挺庞,所以線程很快執(zhí)行完run 方法晰赞。然后線程exit,導(dǎo)致奔潰(在一個(gè)退出的線程选侨,當(dāng)然這個(gè)時(shí)候線程沒有釋放掖鱼,執(zhí)行方法奔潰)
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[thread start];
[self performSelector:@selector(stopThread) onThread:thread withObject:nil waitUntilDone:YES];
}
- (void)stopThread {
CFRunLoopStop(CFRunLoopGetCurrent());//該方法可以釋放掉該線程。
}
- (void)run {
@autoreleasepool {
NSLog(@"current thread = %@", [NSThread currentThread]);
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
if (!self.emptyPort) {
self.emptyPort = [NSMachPort port];
}
[runLoop addPort:self.emptyPort forMode:NSDefaultRunLoopMode];
// 下面這兩種寫法都不可取
// [runLoop run];
// [runLoop runMode:NSRunLoopCommonModes beforeDate:[NSDate distantFuture]];
CFRunLoopRun();//通過這種方法開啟runloop可以使線程常駐后臺并且線程可以釋放掉援制。
NSLog(@"run over");
}
}