iOS之创建一个常驻线程

常驻线程有什么用呢?
让一个一直存在的子线程,等待其他线程发来消息,处理其他事件。

注意 :不要使用GCD的global队列创建常驻线程
原因:global全局队列,整个工程共用的队列,队列里的所有线程都会放进一个线程池中,当线程池满了的时候,就会进入等待

状态,后面加进来的block就不会创建新的线程执行了 等待前面的任务执行完成,才会继续执行。如果线程池中的线程长时间不结束,后续堆积的任务会越来越多

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
@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];
//// 这里主要是监听某个 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]];

}