runLoop创建一个常驻线程,多次用到子线程去处理事件,避免频繁的创建,销毁线程,每条线程都有一个RunLoop,他只有能获取到RunLoop.主线程也是通过创建(main函数中)才有的RunLoop
- (void)viewDidLoad {
[super viewDidLoad];
[self threadTest];
}
- (void)threadTest{
NSThread *subThread = [[NSThread alloc] initWithTarget:self selector:@selector(subThreadEntryPoint) object:nil];
[subThread setName:@"TestThread"];
[subThread start];
self.subThread = subThread;
}
//子线程启动后,启动runloop
- (void)subThreadEntryPoint{
@autoreleasepool {
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
//如果注释了下面这一行,子线程中的任务并不能正常执行
//1.开启RunLoop死循环
[runLoop addPort:[NSMachPort port] forMode:NSRunLoopCommonModes];
//2.当前RunLoop,并不是创建新的RunLoop,RunLoop是懒加载的过程,只有第一次是创建,虽然是死循环,但是可以执行该线程外(在此子线程上)的消息
[[NSRunLoop currentRunLoop] run];
//3.通过控制_finished值来中指RunLoop,或者更粗暴的终止线程[NSThread exit];
while(!_finished) {
[[NSRunLoop currentRunLoop]runUntilDate:[NSDatedateWithTimeIntervalSinceNow:0.0001]];
}
NSLog(@"启动RunLoop前--%@",runLoop.currentMode);
[runLoop run];
}
//子线程任务
- (void)subThreadOpetion{
NSLog(@"启动RunLoop后--%@",[NSRunLoop currentRunLoop].currentMode);
NSLog(@"%@----子线程任务开始",[NSThread currentThread]);
[NSThread sleepForTimeInterval:3.0];//模拟事件}
NSLog(@"%@----子线程任务结束",[NSThread currentThread]);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self performSelector:@selector(subThreadOpetion) onThread:self.subThread
withObject:nil waitUntilDone:NO];
}
}