1.併發指的是在同一時間兩個或兩個以上的任務同時執行並且搶佔統一資源的過程
如果只有一個cpu或許併發就不存在了,但是科技的進步帶了併發處理這個問題,因爲現在手機雙核、四核乃至八核(三星、魅族)
首先介紹個概念:GCD(Grand Central Dispatch)我的理解就是在同一時間重要資源的派遣處理,是底層的C的用於處理塊兒的接口,主要用預處理多任務其中的一條任務是有那個處理器處理。GCD的核心就是一個處理隊列,也可以說是一個線程池
1)主線程隊列:所有的任務都都是在主隊列完成的,大部分是處理UI的東西,可以用dispatch_get_main_queue方法返回到主隊列裏面,一個application只有一個主線程隊列
2)併發隊列:dispatch_get_global_queue獲得處理併發隊列的handle
3) 串性隊列:一FIFO模式進行處理,dispatch_queue_create創建該隊列,dispatch_release釋放該隊列
任務分配給不同的隊列有兩種方法,第一:通過塊,第二:通過C方法
2.處理和UI相關的任務:用dispatch_get_main_queue得到主線程
dispatch_async:執行塊兒
dispatch_async_f :處理C程序
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_async(mainQueue, ^{
[[[UIAlertView alloc]initWithTitle:@"GCD" message:@"Amazing" delegate:nil cancelButtonTitle:@"NO" otherButtonTitles:@"YES", nil] show];
});
3.同步任務下載一個圖片,因爲每個線程可能在搶佔資源,所以有時圖片不能顯示,代碼如下
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^{
__block UIImage *img = nil;
dispatch_async(concurrentQueue, ^{
NSString *urlAsString = @"http://f.hiphotos.baidu.com/image/w%3D2048/sign=f57cca190bf79052ef1f403e38cbd6ca/c75c10385343fbf267c91f29b27eca8064388fd7.jpg";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSError *downloadError = nil;
NSData *imgData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&downloadError];
if(downloadError==nil&&imgData!=nil)
{
img = [UIImage imageWithData:imgData];
NSLog(@"data is loading...");
}
else if(downloadError!=nil)
{
NSLog(@"%@",downloadError);
}else
{
NSLog(@"No data could get downloaded form the url");
}
});
dispatch_async(dispatch_get_main_queue()
, ^{
if(img!=nil)
{
UIImageView *imgView = [[UIImageView alloc]initWithFrame:self.view.bounds];
[imgView setImage:img];
[imgView setContentMode:UIViewContentModeScaleAspectFill];
[self.view addSubview:imgView];
}
else
{
NSLog(@"Image is not download.Nothing to dispaly");
}
});
});
(明天再寫~~ 今天就學到這裏!!!學習真的是件愉快的實情~~~~~)