多线程的简单应用

全局并发队列//添加touch事件显示图片 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ //1获得主队列 线程之间的通讯 //异步并行 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ //执行操作 NSString *str=@"http://a.hiphotos.baidu.com/baike/c0%3Dbaike150%2C5%2C5%2C150%2C50/sign=1dc843d302087bf469e15fbb93ba3c49/6a63f6246b600c338719a2501a4c510fd8f9a1c1.jpg"; NSURL *url=[NSURL URLWithString:str]; NSData *data=[NSData dataWithContentsOfURL:url]; UIImage *image=[UIImage imageWithData:data]; //回到主线程显示图片 dispatch_async(dispatch_get_main_queue(), ^{ self.imageview.image=image; }); }); } //------------------- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ //执行耗时的异步操作 dispatch_async(dispatch_get_main_queue(), ^{ //回到主线程,执行ui刷新操作 }); }); 全局并发队列 手动创建串行队列 主队列 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_queue_create("queue名字", nil) dispatch_get_main_queue() 同步sync 没有开启新线程(不具备开启新线程的能力) 串行执行任务 没有开启新线程 串行执行任务 没有开启新线程 串行执行任务(死循环) 异步async 有开启新线程(具备开启新线程的能力) 并发执行任务 有开启新线程 串行执行 任务 有开启新线程 串行执行任务 //点击事件下载图片 两张图片合成一张图片显示 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ dispatch_group_t group=dispatch_group_create(); __block UIImage *image1=nil; dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ image1=[self imageWithurl:@"http://news.xinhuanet.com/mil/2015-08/21/128150615_14401105350931n.jpg"]; }); __block UIImage *image2=nil; dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ image2= [self imageWithurl:@"http://news.xinhuanet.com/mil/2015-08/21/128150615_14401105352811n.jpg"]; }); dispatch_group_notify(group, dispatch_get_main_queue(), ^{ self.image1.image=image1; self.image2.image=image2; //合并图片 UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 120), NO, 0.0); [image1 drawInRect:CGRectMake(0, 0, 100, 120)]; [image2 drawInRect:CGRectMake(100, 0, 100, 120)]; self.addimage.image=UIGraphicsGetImageFromCurrentImageContext(); //关闭上下文 UIGraphicsEndImageContext(); }); } //请求一个图片 -(UIImage *)imageWithurl:(NSString *)urlstr{ //1 NSURL *url=[NSURL URLWithString:urlstr]; NSData *data=[NSData dataWithContentsOfURL:url]; UIImage *image=[UIImage imageWithData:data]; NSLog(@"转图片"); return image; }
posted @ 2015-08-21 19:00  shao621  阅读(155)  评论(0编辑  收藏  举报