一、NSThread 线程间的通讯
- (void)demoAboutNSThread { NSLog(@"demoAboutNSThread %@", [NSThread currentThread]); NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(longTimeOperation) object:nil]; [thread start]; } - (void)longTimeOperation { NSLog(@"longTimeOperation %@", [NSThread currentThread]); [self performSelectorOnMainThread:@selector(mainThreadOperation) withObject:nil waitUntilDone:NO]; } - (void)mainThreadOperation { NSLog(@"mainThreadOperation %@",[NSThread currentThread]); }
二、GCD 线程间通讯
- (void)dispatchDemo { NSLog(@" start %@",[NSThread currentThread]); dispatch_async(dispatch_get_global_queue(, ), ^{ NSLog(@" 耗时从左 %@",[NSThread currentThread]); dispatch_sync(dispatch_get_main_queue(), ^{ NSLog(@" 回到主线程 %@", [NSThread currentThread]); }); }); NSLog(@"end %@",[NSThread currentThread]); }
三、NSOperation 线程间的通讯
- (void)demoAboutNSOperation { NSOperation * block = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"block %@",[NSThread currentThread]); }]; [self.queue addOperation:block]; [self.queue addOperationWithBlock:^{ NSLog(@"耗时操作 %@",[NSThread currentThread]); [[NSOperationQueue mainQueue] addOperationWithBlock:^{ NSLog(@" mainQueue %@",[NSThread currentThread]); }]; }]; }