網上關於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,都是基於消息隊列的模式,一個發,一個收,寫時加鎖,別無更好的辦法了