您的位置:首页 > 理论基础 > 计算机网络

ios 网络编程之多线程

2016-03-02 17:26 549 查看
线程 用来执行 进程中分配的任务 ,一个进程中可以有多个线程,多线程执行任务的效率比单线程执行效率高 ,一个进程中如果线程比较多的花,很容易造成资源浪费,可能会出现卡顿现象,一般适当的使用线程。

在CPU中线程也是一条一条执行的,只是切换线程的时间比较短而已,可以认为是同是执行的,CPU(多核多个寄存器)只是缩短了切换线程的时间而已。

下面 是一个多线程加载多张图片的示例,按顺序执行加载,点击屏幕会停止加载图片。

#import "MoreImageViewController.h"

//一张图片的url地址

#define kUrl @"http://store.storeimages.cdn-apple.com/8748/as-images.apple.com/is/image/AppleInc/aos/published/images/s/38/s38ga/rdgd/s38ga-rdgd-sel-201601?wid=848&hei=848&fmt=jpeg&qlt=80&op_sharpen=0&resMode=bicub&op_usm=0.5,0.5,0,0&iccEmbed=0&layer=comp&.v=1454777389943"

@interface MoreImageViewController ()

{

int imagrIndex;

UIImage *image;

NSMutableArray *threadArray;//盛放线程的数组

}

@end

@implementation MoreImageViewController

- (void)viewDidLoad {

[super viewDidLoad];

self.title = @"多线程加载多张照片";

self.view.backgroundColor = [UIColor whiteColor];

imagrIndex =100;

self.edgesForExtendedLayout = UIRectEdgeNone;

threadArray = [NSMutableArray array];

// 创建多个uiimageview

for (int row=0; row<3; row++) {

for (int list=0; list<2; list++) {

UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10+list*200, 10+row*200, 200, 200)];

imageView.backgroundColor = [UIColor orangeColor];

imageView.tag = imagrIndex++;

imageView.userInteractionEnabled = YES;

[self.view addSubview:imageView];

}

}

// 创建子线程

for (int index =0; index<6; index++) {

// 注意实现退出 加载功能的线程时候,使用alloc init方法创建 子线程

NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(thread:) object:@(index)];

// 开启线程

[thread start];

[threadArray addObject:thread];

}

}

// 通过url加载图片

- (void)thread:(NSNumber *)index{

// 通过线程休眠 让图片实现 按顺序加载

[NSThread sleepForTimeInterval:[index intValue]];

NSThread *thread = [NSThread currentThread];

if (thread.isCancelled==YES) {

[NSThread exit];

}

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:kUrl]];

image = [UIImage imageWithData:data];

// 回到主线程方法

[self performSelectorOnMainThread:@selector(updateUI:) withObject:index waitUntilDone:YES];

}

// 更新UI界面的方法

- (void)updateUI:(NSNumber *)index{

UIImageView *imageView = [self.view viewWithTag:100+[index intValue]];

imageView.image = image;

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

for (int index =0; index<6; index++) {

NSThread *thread = threadArray[index];

if (thread.isFinished==NO) {

//点击屏幕 取消未完成的线程

[thread cancel];

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: