NSRunLoop 就是一直在循环检测,从线程start到线程end,检测inputsource(如点击,双击等操作)同步事件,检测timesource同步事件,检测到输入源会执行处理函数,首先会产生通知,corefunction向线程添加runloop observers来监听事件,意在监听事件发生时来做处理。
perform selector在thread中被序列化执行,这样就缓和了许多在同一个thread中运行多个方法所产生的同步问题。
@interface ViewController ()
{
NSThread *A;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton*button =[[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 50)];
[button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
button.backgroundColor= [UIColor blackColor];
A = [[NSThread alloc] initWithTarget:self selector:@selector(AThread) object:nil]; //生成线程A
[A start];
}
-(void)buttonAction
{
if (A) {
[self performSelector:@selector(BThread) onThread:A withObject:nil waitUntilDone:YES modes:@[@"CustomRunLoopMode"]];
}
}
-(void)BThread
{
//<NSThread: 0x7a17ae40>{number = 2, name = (null)}
}
-(void)AThread
{
//<NSThread: 0x7a17ae40>{number = 2, name = (null)}
BOOL isRunning = NO;
do {
isRunning = [[NSRunLoop currentRunLoop] runMode:@"CustomRunLoopMode" beforeDate:[NSDate distantFuture]];
} while (!isRunning);
/*
BThread end
continue code ...
*/
//防止线程A被释放后调用
A = nil;
}