多线程开发Demo
1.dispatch_async方法确定在哪个线程队列中执行哪些操作,操作用block实现。
2.DISPATCH_QUEUE_PRIORITY_DEFAULT默认线程队列,dispatch_get_main_queue()主线程队列。
3.block中需要修改公共变量,则变量需要用__block修饰,只读的变量可以不用__block,而是在block中复制一个同名变量共block使用。
4.定义dispatch_group_t来执行可并行执行的代码块,系统会自动选择某个合适的处理器处理,提高程序性能。
5.通过方法dispatch_group_async分发并行执行的代码块,通过方法dispatch_group_notify通知所有分发块均执行结束后的动作。
代码如下:
- (void)doWork:(id)sender{
_startButton.enabled = NO;
_startButton.alpha = 0.6;
_resultsLabel.text = @"";
_timeLabel.text = @"Waiting ...";
[_spineer startAnimating];
NSDate *startTime = [NSDate date];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString *fetchdData = [self fetchSomethingFromSever];
NSString *processData = [self processData:fetchdData];
__block NSString *firstResult = nil;
__block NSString *secondResult = nil;
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
firstResult = [self calculateFirstResult:processData];
});
dispatch_group_async(group, queue, ^{
secondResult = [self calculateSecondResult:processData];
});
dispatch_group_notify(group, queue, ^{
NSString *resultSummary = [NSString stringWithFormat:@"processData: [%@] firstResult: [%@] SectionResult: [%@] ",processData,firstResult,secondResult];
NSDate *endTime = [NSDate date];
_resultsLabel.text = resultSummary;
_timeLabel.text = [NSString stringWithFormat:@"Complete in %f seconds",[endTime timeIntervalSinceDate:startTime]];
[_spineer stopAnimating];
_startButton.enabled = YES;
_startButton.alpha = 1.0;
});
// 唤起主线程
dispatch_async(dispatch_get_main_queue(), ^{
});
});
}