• 多线程的简单应用


    全局并发队列//添加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; }
  • 相关阅读:
    wmware虚拟机的克隆
    解决SecureCRT无法用非root账号登录ssh
    Docker容器操作
    Docker镜像操作
    Docker的安装和启动
    linux安装tomcat
    POJ 2456 Aggressive cows ( 二分搜索)
    POJ 1064 Cable master (二分查找)
    2008 APAC local onsites C Millionaire (动态规划,离散化思想)
    贿赂囚犯 Bribe the prisoners ( 动态规划+剪枝)
  • 原文地址:https://www.cnblogs.com/shao621/p/4748120.html
Copyright © 2020-2023  润新知