常駐線程有什么用呢?
讓一個一直存在的子線程,等待其他線程發(fā)來消息,處理其他事件。
注意 :不要使用GCD的global隊列創(chuàng)建常駐線程
原因:global全局隊列,整個工程共用的隊列,隊列里的所有線程都會放進(jìn)一個線程池中,當(dāng)線程池滿了的時候,就會進(jìn)入等待狀態(tài),后面加進(jìn)來的block就不會創(chuàng)建新的線程執(zhí)行了 等待前面的任務(wù)執(zhí)行完成,才會繼續(xù)執(zhí)行。如果線程池中的線程長時間不結(jié)束,后續(xù)堆積的任務(wù)會越來越多
@interface LongThreadDemoController ()
@property (nonatomic, strong) NSThread *thread;
@end
@implementation LongThreadDemoController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"常駐線程Demo";
}
- (void)threadRunloopPoint:(id)__unused object{
NSLog(@"%@",NSStringFromSelector(_cmd));
@autoreleasepool {
[[NSThread currentThread] setName:@"changzhuThread"];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
//// 這里主要是監(jiān)聽某個 port,目的是讓這個 Thread 不會回收
[runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
[runLoop run];
}
}
- (NSThread *)thread{
if(!_thread){
_thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadRunloopPoint:) object:nil];
[_thread start];
}
return _thread;
}
- (void)test{
NSLog(@"%s",__func__);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO modes:@[NSDefaultRunLoopMode]];
}
個人博客地址:https://youyou0909.github.io