//  ViewController.m
#import "ViewController.h" @interface ViewController ()
{
//任务队列,能够自动管理多个任务(NSOperation的对象)
NSOperationQueue *_operationQueue;
}
@end @implementation ViewController #define kUrlString @"http://jsonfe.funshion.com/?pagesize=10&cli=iphone&page=1&src=phonemedia&ta=0&ver=1.2.8.2&jk=0"
#define kImageString @"http://img1.funshion.com/attachment/fs/112/200/112200.jpg?1387939530" - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_operationQueue = [[NSOperationQueue alloc] init];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setTitle:@"thread" forState:UIControlStateNormal];
[btn setFrame:CGRectMake(,,,)];
[btn addTarget:self action:@selector(threadMethod) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn]; UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn1 setTitle:@"operation" forState:UIControlStateNormal];
[btn1 setFrame:CGRectMake(,,,)];
[btn1 addTarget:self action:@selector(operationMethod) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn1]; UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn2 setTitle:@"GCD" forState:UIControlStateNormal];
[btn2 setFrame:CGRectMake(,,,)];
[btn2 addTarget:self action:@selector(gcdMethod) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn2]; /*严重的费时操作 等好久才能显示
for (int i=0; i<20; i++) {
for (int j=0; j<50; j++) { NSURL *url =[NSURL URLWithString:kImageString];
//同步下载数据的方法
NSData *data = [NSData dataWithContentsOfURL:url];
// UIImage *ima = [UIImage imageWithData:data];
UIImageView *ima=[[UIImageView alloc]initWithFrame:CGRectMake(0+j*3, i*3, 2, 2)];
ima.image=[UIImage imageWithData:data];
[self.view addSubview:ima];
}
}
*/
} //gcd是iOS4.0之后出现的技术,Grand Centeral Dispatch->苹果高度封装的处理多线程的技术,可以理解为block版本的NSOperation和NSOperationQueue
- (void)gcdMethod{
//gcd中有一个主队列,用于管理和调度主线程;有三个优先级的全局队列,来管理子线程
//dispatch_get_global_queue 第一个参数为设置队列的优先级 0为默认优先级 2为最高优先级 -1为低优先级;第二个参数为预留参数,一般也写成0
dispatch_async(dispatch_get_global_queue(, ), ^{
//利用全局队列,在主线程之外单独开辟了一个线程,线程执行block方法
NSURL *url =[NSURL URLWithString:kUrlString];
NSString *result = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
if (result) {
//通过主队列回到主线程,主线程中执行block
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"result:%@",result);
}); }else{
NSLog(@"error!");
}
});
} //NSOperation,以任务为导向的线程,可以叫做开启一个任务
//NSOperationQueue 任务队列,来维护多个任务(线程)
- (void)operationMethod{
//一般使用NSOperation的子类来进行多线程操作
NSInvocationOperation *oper = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(downloadImage) object:nil];
//[oper start]; 需要调用此方法 oper对象才会开辟线程,让线程执行sel方法
//添加到队列后,队列会自动让oper对象开辟线程并执行sel方法
[_operationQueue addOperation:oper];
//[_operationQueue addOperations:<#(NSArray *)#> waitUntilFinished:<#(BOOL)#>]
}
//NSThread
- (void)threadMethod{
//NSThread iOS中最早出现的线程类
//detachNewThreadSelector 在主线程之外单独开辟一个线程来执行sel方法
//toTarget sel所在的对象
[NSThread detachNewThreadSelector:@selector(downloadString) toTarget:self withObject:nil];
} //同步下载一张图片
- (void)downloadImage{
@autoreleasepool {
NSURL *url =[NSURL URLWithString:kImageString];
//同步下载数据的方法
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
if (image) {
//给主线程
[self performSelectorOnMainThread:@selector(receiveImage:) withObject:image waitUntilDone:NO];
//线程之间的通信
//[self performSelector:<#(SEL)#> onThread:<#(NSThread *)#> withObject:<#(id)#> waitUntilDone:<#(BOOL)#>]
}else{
NSLog(@"下载失败!");
}
}
} - (void)receiveImage:(UIImage *)image{
//colorWithPatternImage 此方法比较消耗GPU,需要慎用,而且要求view与imagesize 一致
// self.view.backgroundColor = [UIColor colorWithPatternImage:image]; //多线程可以解决费时操作 比普通的下载图片快很多
for (int i=; i<; i++) {
for (int j=; j<; j++) {
UIImageView *ima=[[UIImageView alloc]init];
ima.frame=CGRectMake(+j*, i*, , );
ima.image=image;
[self.view addSubview:ima];
}
}
} //线程的生命周期与函数一致,函数开始则线程开始;函数执行完毕,线程自动结束
//在主线程之外开辟的线程叫子线程或者工作线程
- (void)downloadString{
//执行耗时操作
//主线程的自动释放池,子线程无法使用,需要自己手动添加
@autoreleasepool {
NSURL *url = [NSURL URLWithString:kUrlString];
//同步请求数据的方法,会阻塞当前线程
NSString *result = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
if (result) {
//需要将数据给到UI主线程,理论上子线程没有被分配足够的资源来操作UI,所以对于UI的操作一般在主线程中完成。
//子线程和主线程之间的通信
[self performSelectorOnMainThread:@selector(receiveString:) withObject:result waitUntilDone:NO]; //[self performSelector:<#(SEL)#> withObject:<#(id)#>]
}else{
NSLog(@"load error!");
}
}
} //在主线程中执行的方法
- (void)receiveString:(NSString *)result{
NSLog(@"ui result:%@",result);
//操作UI也在主线程中
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end

thread、operation、GCD的更多相关文章

  1. TensorFlow中的Session、Graph、operation、tensor

    TensorFlow中的Session.Graph.operation.tensor

  2. iOS开发笔记5:多线程之NSThread、NSOperation及GCD

    这篇主要总结下iOS开发中多线程的使用,多线程开发一般使用NSThread.NSOperation及GCD三种方式,常用GCD及NSOperation. 1.NSThread 创建线程主要有以下三种方 ...

  3. 多线程相关(pthread 、NSThread 、GCD、NSOperation)

    进程 进程是指在系统中正在运行的一个应用程序 线程 1个进程要想执行任务,必须得有线程(每1个进程至少要有1条线程) 1个线程中任务的执行是串行的(执行完上一个才能执行下一个) 多线程 1个进程中可以 ...

  4. iOS开发之多线程(NSThread、NSOperation、GCD)

    整理一些多线程相关的知识. 并行 & 并发 1.并行:并行是相对于多核而言的,几个任务同时执行.2.并发:并发是相对于单核而言的,几个任务之间快速切换运行,看起来像是"同时" ...

  5. iOS开发之多线程技术(NSThread、OperationQueue、GCD)

    在前面的博客中如果用到了异步请求的话,也是用到的第三方的东西,没有正儿八经的用过iOS中多线程的东西.其实多线程的东西还是蛮重要的,如果对于之前学过操作系统的小伙伴来说,理解多线程的东西还是比较容易的 ...

  6. iOS开发:深入理解GCD 第二篇(dispatch_group、dispatch_barrier、基于线程安全的多读单写)

    Dispatch Group在追加到Dispatch Queue中的多个任务处理完毕之后想执行结束处理,这种需求会经常出现.如果只是使用一个Serial Dispatch Queue(串行队列)时,只 ...

  7. Linux Process/Thread Creation、Linux Process Principle、sys_fork、sys_execve、glibc fork/execve api sourcecode

    相关学习资料 linux内核设计与实现+原书第3版.pdf(.3章) 深入linux内核架构(中文版).pdf 深入理解linux内核中文第三版.pdf <独辟蹊径品内核Linux内核源代码导读 ...

  8. 那些年我们一起追逐的多线程(Thread、ThreadPool、委托异步调用、Task/TaskFactory、Parallerl、async和await)

    一. 背景 在刚接触开发的头几年里,说实话,根本不考虑多线程的这个问题,貌似那时候脑子里也有没有多线程的这个概念,所有的业务都是一个线程来处理,不考虑性能问题,当然也没有考虑多线程操作一条记录存在的并 ...

  9. python中thread的setDaemon、join的用法的代码

    下面内容是关于python中thread的setDaemon.join的用法的内容. #! /usr/bin/env python import threading import time class ...

随机推荐

  1. Android之Intent深入

    Android中的意图包含多种用法,本文主要包括以下内容 显式意图 隐匿意图 要求结果回传的意图 显式意图 :必须指定要激活的组件的完整包名和类名 (应用程序之间耦合在一起) 一般激活自己应用的组件的 ...

  2. centos7下yum安装mysql

    CentOS 7的yum源中貌似没有正常安装mysql时的mysql-sever文件,需要去官网上下载   # wget http://dev.mysql.com/get/mysql-communit ...

  3. 蓝桥杯 算法训练 区间k大数查询(水题)

    算法训练 区间k大数查询 时间限制:1.0s   内存限制:256.0MB 问题描述 给定一个序列,每次询问序列中第l个数到第r个数中第K大的数是哪个. 输入格式 第一行包含一个数n,表示序列长度. ...

  4. cf 559a **

    题意:给一个六边形,求小三角形个数 #include<cstdio> #include<iostream> #include<algorithm> #include ...

  5. Oracle 连接 Visual Studio 的工具

    Oracle 连接 Visual Studio 的工具 ① ② ③

  6. ML 02、监督学习

    机器学习算法原理.实现与实践——监督学习 机器学习包括监督学习.非监督学习.半监督学习及强化学习,这里先讨论监督学习. 监督学习的任务是学习一个模型,使模型能够对任意给定的输入,对其相应的输出做出一个 ...

  7. 【codevs2822】爱在心中 tarjan 缩点+理解

    [codevs2822]爱在心中 2014年1月26日5580 题目描述 Description “每个人都拥有一个梦,即使彼此不相同,能够与你分享,无论失败成功都会感动.爱因为在心中,平凡而不平庸, ...

  8. AppleWatch开发教程之Watch应用对象新增内容介绍以及编写运行代码

    AppleWatch开发教程之Watch应用对象新增内容介绍以及编写运行代码 添加Watch应用对象时新增内容介绍 Watch应用对象添加到创建的项目中后,会包含两个部分:Watch App 和 Wa ...

  9. 2015ACM/ICPC亚洲区长春站 B hdu 5528 Count a * b

    Count a * b Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)Tot ...

  10. (centos)linux下访问双系统windows7文件系统

    fdisk -l 无法挂载 NTFS格式的分区:mount: unknown filesystem type ‘ntfs’.   问题:       # mount –t ntfs /dev/sdb1 ...