网上关于runloop的文章不计其数,再此,贴个自认为讲的比较简单明了的文章
个人理解:
ios的runloop应该是类似于线程之间的消息监听+队列(队列于外部不透明,支持多重send消息模式,perform selector,timer,UI事件等等)
和android的Looper非常相似,和windows的消息循环也很类似,具体底层实现不关注,直接贴测试代码
#import "ViewController.h" @interface ViewController () @property(nonatomic, strong) NSThread *thread;
@property(nonatomic, strong) NSThread *msgThread; @end @implementation ViewController - (void) viewDidLoad{
[super viewDidLoad]; [self initMsgThread];
} - (void) initMsgThread{ self.msgThread = [[NSThread alloc]initWithTarget:self selector:@selector(msgThreadInitFunc) object:nil];
[self.msgThread start];
} - (void) msgThreadInitFunc{
NSLog(@"msgThreadInitFunc run, %@",[NSThread currentThread]); [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run]; NSLog(@"msgThreadInitFunc run"); } //******************************************************************************************************************
- (void) postMsgToThread{
[[[NSThread alloc]initWithTarget:self selector:@selector(asyncPostMsgToThread) object:nil] start];
} - (void) asyncPostMsgToThread{
[self performSelector:@selector(onThreadMsgProc) onThread:self.msgThread withObject:nil waitUntilDone:NO];
} - (void) onThreadMsgProc{
NSLog(@"do some work %@, %s", [NSThread currentThread], __FUNCTION__);
} //******************************************************************************************************************
- (void) startTimerOnThread{
self.thread = [[NSThread alloc]initWithTarget:self selector:@selector(asyncStartTimerOnThread) object:nil];
[self.thread start];
} - (void) asyncStartTimerOnThread{
[self performSelector:@selector(asyncStartTimer) onThread:self.thread withObject:nil waitUntilDone:NO]; // [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
} - (void) asyncStartTimer{
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(timerFired:)userInfo:nil repeats:YES];
} - (void) timerFired:(id)timer{
NSLog(@"on thread timer %s",__FUNCTION__);
} //******************************************************************************************************************
- (IBAction)testButtonTapped:(id)sender {
// [self postMsgToThread];
[self startTimerOnThread];
} @end
当然用block也是一样的,子线程必须创建runloop来监听消息,否则这个子线程是无法处理类似performSelector,NSTimer之类的消息的
线程之间通信,cocos2dx,u3d,ios,android,win32,都是基于消息队列的模式,一个发,一个收,写时加锁,别无更好的办法了