一、NSThread 线程间的通讯
1 - (void)demoAboutNSThread 2 { 3 NSLog(@"demoAboutNSThread %@", [NSThread currentThread]); 4 NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(longTimeOperation) object:nil]; 5 [thread start]; 6 } 7 8 - (void)longTimeOperation 9 { 10 NSLog(@"longTimeOperation %@", [NSThread currentThread]); 11 [self performSelectorOnMainThread:@selector(mainThreadOperation) withObject:nil waitUntilDone:NO]; 12 } 13 14 - (void)mainThreadOperation 15 { 16 NSLog(@"mainThreadOperation %@",[NSThread currentThread]); 17 }
二、GCD 线程间通讯
1 - (void)dispatchDemo 2 { 3 NSLog(@" start %@",[NSThread currentThread]); 4 5 dispatch_async(dispatch_get_global_queue(0, 0), ^{ 6 NSLog(@" 耗时从左 %@",[NSThread currentThread]); 7 8 dispatch_sync(dispatch_get_main_queue(), ^{ 9 NSLog(@" 回到主线程 %@", [NSThread currentThread]); 10 }); 11 12 }); 13 14 NSLog(@"end %@",[NSThread currentThread]); 15 }
三、NSOperation 线程间的通讯
1 - (void)demoAboutNSOperation 2 { 3 NSOperation * block = [NSBlockOperation blockOperationWithBlock:^{ 4 NSLog(@"block %@",[NSThread currentThread]); 5 }]; 6 7 [self.queue addOperation:block]; 8 9 [self.queue addOperationWithBlock:^{ 10 NSLog(@"耗时操作 %@",[NSThread currentThread]); 11 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 12 NSLog(@" mainQueue %@",[NSThread currentThread]); 13 }]; 14 }]; 15 16 17 }
时间: 2024-10-12 20:27:45