標籤:記憶體泄露 cpu log oid val 線程 應該 form imei
一、接著上一篇通過NSThread可以方便的建立一個線程,並且啟動線程的Runloop,線上程體中執行一個while迴圈
然後我們就可以方便得利用這個線程了
- (void)threadRun:(NSThread *)thread{ NSLog(@"Thread run"); NSLog(@"hello 1"); while (!_isCancelled && [currentRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) { NSLog(@"hello 2"); _isCancelled = [currentThread isCancelled]; } NSLog(@"hello 3");}
二、那我們應該如何正確結束一個NSThread呢
NSThread結束可以調用兩個方法,一個是對象方法-[Thread cancel],這個方法標記NSThraed的屬性isCanceled為YES,那麼通過配合上面的迴圈,線程體本身就結束了。
另外一個方法是+[Thread exit],注意這個方法需要在NSThraed為當前線程中調用,該方法比較暴力不管線程中的任務是否還在執行,
直接結束,也不管runloop,因此可能帶來記憶體泄露。
三、NSRunloop
- (BOOL)runMode:(NSRunLoopMode)mode beforeDate:(NSDate *)limitDate;
根據官方文檔,上面的API在Runloop中沒有事件來源或者timer的時候,該方法會立即返回NO,所以在執行這個線程體的迴圈時候,需要先加入一個timer
保證while迴圈不會結束,也就保證了線程不會結束
- (void)threadRun:(NSThread *)thread{ NSLog(@"Thread run"); _liveTimer = [NSTimer scheduledTimerWithTimeInterval:[[NSDate distantFuture] timeIntervalSinceNow] target:self selector:@selector(ignore:) userInfo:nil repeats:YES]; NSThread *currentThread = [NSThread currentThread]; NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop]; _isCancelled = [currentThread isCancelled]; NSLog(@"hello 1"); while (!_isCancelled && [currentRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) { NSLog(@"hello 2"); _isCancelled = [currentThread isCancelled]; NSLog(@"hello 4"); } NSLog(@"hello 3");}
上面的含義另外一層意思就是,只要迴圈結束,線程體結束,那麼NSThread也就結束,NSThread中的Runloop也結束了,而不管Runloop中的什麼事件有沒有執行完
那麼一旦Runloop起來之後,將Runloop中的事件全部移除之後,Runloop是否會自動結束呢
- (void)stopThread:(NSThread *)thread{ //[self performSelector:@selector(stopThread:) withObject:thread afterDelay:5]; [_liveTimer invalidate]; //CFRunLoopStop(CFRunLoopGetCurrent()); //[thread cancel]; //_isCancelled = YES; //while ([thread isExecuting] == YES) usleep(10000); NSLog(@"stop done"); }- (void)ignore:(NSTimer *)timer{ NSLog(@"ignore");}- (void)threadRun:(NSThread *)thread{ NSLog(@"Thread run"); //佔用0%的CPU _liveTimer = [NSTimer scheduledTimerWithTimeInterval:[[NSDate distantFuture] timeIntervalSinceNow] target:self selector:@selector(ignore:) userInfo:nil repeats:YES]; NSThread *currentThread = [NSThread currentThread]; NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop]; _isCancelled = [currentThread isCancelled]; NSLog(@"hello 1"); while (/*!_isCancelled && */[currentRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) { NSLog(@"hello 2"); //_isCancelled = [currentThread isCancelled]; NSLog(@"hello 4"); } NSLog(@"hello 3");}
上面的代碼中去除了cancel標記,那麼即使timer移除,這個while還在一直保持迴圈,因為- (BOOL)runMode:(NSRunLoopMode)mode beforeDate:(NSDate *)limitDate;不會返回第二次值
那麼如果沒有while迴圈了呢,這個線程體也就真正結束啦
iOS 如何保持線程一直在運轉(二)