1.GCD(Grand Centrol Dispath)
并行:宏觀和微觀都是兩個人再拿著兩把鐵鍬在挖坑,1小時挖兩個大坑
并發:宏觀上是感覺他們都在挖坑,微觀是他們是在使用1把鐵鍬挖坑,1小時后他們挖了兩個小坑。
總結:就單個cpu來講,大部份進程是并發進行的,就是1把鐵鍬,你1下我1下,只是間隔時間較短,用戶感覺不到而已。
利用:
GCD包括:
(1)實際使用中( 而系統默許就有1個串行隊列main_queue和并行隊列global_queue:
//dispatch_get_global_queue(0, 0)第1個0是優先級,第2個保存字段
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//在這里可以是數據要求
NSString* result = [self requestData:parameter];
//在這里返回主線程刷新數據
dispatch_async(dispatch_get_main_queue(), ^{
[mainTableView reloadData];
});
});
舉例說明:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL * url = [NSURL URLWithString:@"http://www.baidu.com"];
NSError * error;
NSString * data = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
if (data != nil) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"call back, the data is: %@", data);
});
} else {
NSLog(@"error when download:%@", error);
}
});
(2)也能夠自己創建(我是不怎樣用)
串行隊列,顧名思義,1串嘛,那就得并發履行嘍
//自己創建serial queue
dispatch_queue_t queue = dispatch_queue_create("com.class15.queue", DISPATCH_QUEUE_SERIAL);
//異步履行線程
dispatch_async(queue, ^{
NSLog(@"任務1:%@ %d", [NSThread currentThread],[NSThread currentThread].isMainThread);
});
并行隊列通過dispatch_get_global_queue獲得,由系統創建3個不同優先級的dispatch queue
//創建自己的隊列
dispatch_queue_t queue = dispatch_queue_create("com.class15.comcrrentQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"任務1:%@ %d", [NSThread currentThread],[NSThread currentThread].isMainThread);
});