IOS线程数据篇2之多线程:NSThread NSOperation GCD(一)

栈空间是非常宝贵的,主线程只能开辟1M。子线程只有512K。android的栈空间好像只有2M。android的堆空间有16M、32M、64M的。

线程运行完之后,ARC下内存自动回收。线程不能被杀死,只能暂停。

优点:将耗时的任务分配到其他线程执行,由主线程负责统一更新界面会使应用程序更加流畅,用户体验更好

缺点:新建线程会消耗内存空间和CPU时间,线程太多会降低系统的运行性能。

多线程技术是为了并发执行多项任务,不会提高单个算法本身的执行效率。

IOS下线程使用的三种方式:

NSThread:简单使用比较方便,但线程管理比较复杂,一般不用。

NSOperation/NSOperationQueue :是使用GCD实现的一套Objective-C的API,提供了一些在GCD中不容易实现的特性,如:限制最大并发数量、操作之间的依赖关系

GCD —— Grand Central Dispatch 大中央 调度分发。是基于C语言的底层API,用Block定义任务。

GCD的基本思想是就将操作s放在队列s中去执行,队列就是负责调度的!谁空闲,就把任务给谁!

1 先看这个简单的NSThread:

虽然这个比较简单,在线程之间管理不方便,但同时这个也提供了一些简单易用的方法:

在后台运行

-(void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg 

在主线程中运行

– performSelectorOnMainThread:withObject:waitUntilDone:

在某一个线程中执行

– performSelector:onThread:withObject:waitUntilDone:modes:

在当前的线程延迟执行

performSelector:withObject:afterDelay获取当前线程信息


[NSThread currentThread]

线程休眠一段时间


[NSThread sleepForTimeInterval:2.0f];

performSelector:withObject:afterDelayNSThread线程的使用

NSThread*thread = [[NSThreadalloc]initWithTarget:selfselector:@selector(mutableThread:)object:@"test"];

[thread start];
[NSThreaddetachNewThreadSelector:@selector(mutableThread:)toTarget:selfwithObject:nil]; 

2 队列的使用

队列常用在以下几个方面

// 利⽤用线程队列添加多个线程并指定线程的优先级

NSOperationQueue*queue = [[NSOperationQueue alloc]init];

NSInvocationOperation*thread01 = [[NSInvocationOperationalloc]initWithTarget:selfselector:@selector(mutableThread01:)object:nil];

NSInvocationOperation*thread02 = [[NSInvocationOperationalloc]initWithTarget:selfselector:@selector(mutableThread02:)object:nil];

// 设置最⼤大并发数,以及线程的优先级别。

queue.maxConcurrentOperationCount= 1;

thread02.queuePriority= NSOperationQueuePriorityHigh;

[queue addOperation:thread01];

[queue addOperation:thread02]; 


NSOperationQueue  NSBlockOperation

    NSBlockOperation *threadop1 = [NSBlockOperation blockOperationWithBlock:^{

    }];

    NSBlockOperation *threadop2 = [NSBlockOperation blockOperationWithBlock:^{

    }];


    [threadop2 addDependency:threadop1];

    [queue addOperation:op1];

    [[NSOperationQueue mainQueue] addOperation:op4];

    UI更新只能在主线程中使用。利用队列可以设置并发个数,可以设置优先级,可以设置依赖关系(可以跨队列)。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值