每一个iOS应用程序都有个专门用来更新显示UI界面、处理用户的触摸事件的主线程,所以不能将其余太耗时的操做放在主线程中执行,否则会形成主线程堵塞(出现卡机现象),带来极坏的用户体验。通常的解决方案就是将那些耗时的操做放到另一个线程中去执行,多线程编程是防止主线程堵塞,增长运行效率的最佳方法java
iOS支持多个层次的多线程编程,层次越高的抽象程度越高,使用也越方便,也是苹果最推荐使用的方法。下面根据抽象层次从低到高依次列出iOS所支持的多线程编程方法:编程
1.Thread :是三种方法里面相对轻量级的,但须要管理线程的生命周期、同步、加锁问题,这会致使必定的性能开销
2.Cocoa Operations:是基于OC实现的,NSOperation以面向对象的方式封装了须要执行的操做,没必要关心线程管理、同步等问题。NSOperation是一个抽象基类,iOS提供了两种默认实现:NSInvocationOperation和NSBlockOperation,固然也能够自定义NSOperation
3.Grand Central Dispatch(简称GCD,iOS4才开始支持):提供了一些新特性、运行库来支持多核并行编程,它的关注点更高:如何在多个cpu上提高效率
多线程
这篇文章简单介绍了第一种多线程编程的方式,主要是利用NSThread这个类,一个NSThread实例表明着一条线程app
1、NSthread的初始化ide
1.动态方法性能
[java] view plaincopyatom
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument; spa
[java] view plaincopy.net
// 初始化线程 线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
// 设置线程的优先级(0.0 - 1.0,1.0最高级)
thread.threadPriority = 1;
// 开启线程
[thread start];
参数解析:
selector :线程执行的方法,这个selector最多只能接收一个参数
target :selector消息发送的对象
argument : 传给selector的惟一参数,也能够是nil
2.静态方法
[java] view plaincopy
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;
[java] view plaincopy
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
// 调用完毕后,会立刻建立并开启新线程
3.隐式建立线程的方法
[java] view plaincopy
[self performSelectorInBackground:@selector(run) withObject:nil];
2、获取当前线程
[java] view plaincopy
NSThread *current = [NSThread currentThread];
3、获取主线程
[java] view plaincopy
NSThread *main = [NSThread mainThread];
4、暂停当前线程
[java] view plaincopy
// 暂停2s
[NSThread sleepForTimeInterval:2];
// 或者
NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]];
[NSThread sleepUntilDate:date];
5、线程间的通讯
1.在指定线程上执行操做
[java] view plaincopy
[self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];
2.在主线程上执行操做
[java] view plaincopy
[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];
3.在当前线程执行操做
[java] view plaincopy
[self performSelector:@selector(run) withObject:nil];
6、优缺点
1.优势:NSThread比其余两种多线程方案较轻量级,更直观地控制线程对象
2.缺点:须要本身管理线程的生命周期,线程同步。线程同步对数据的加锁会有必定的系统开销
--------------------------------------------
--------------另一个博客的补充----------
咱们演示一个经典的卖票的例子来说NSThread的线程同步:
.h
[cpp] view plaincopy
#import <UIKit/UIKit.h>
@class ViewController;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
int tickets;
int count;
NSThread* ticketsThreadone;
NSThread* ticketsThreadtwo;
NSCondition* ticketsCondition;
NSLock *theLock;
}
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ViewController *viewController;
@end
[cpp] view plaincopy
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
tickets = 100;
count = 0;
theLock = [[NSLock alloc] init];
// 锁对象
ticketsCondition = [[NSCondition alloc] init];
ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[ticketsThreadone setName:@"Thread-1"];
[ticketsThreadone start];
ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[ticketsThreadtwo setName:@"Thread-2"];
[ticketsThreadtwo start];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)run{
while (TRUE) {
// 上锁
// [ticketsCondition lock];
[theLock lock];
if(tickets >= 0){
[NSThread sleepForTimeInterval:0.09];
count = 100 - tickets;
NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]);
tickets--;
}else{
break;
}
[theLock unlock];
// [ticketsCondition unlock];
}
}
若是没有线程同步的lock,卖票数多是-1.加上lock以后线程同步保证了数据的正确性。
上面例子我使用了两种锁,一种NSCondition ,一种是:NSLock。 NSCondition我已经注释了。
他们均可以经过
[ticketsCondition signal]; 发送信号的方式,在一个线程唤醒另一个线程的等待。
好比:
[cpp] view plaincopy
#import "AppDelegate.h"
#import "ViewController.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
tickets = 100;
count = 0;
theLock = [[NSLock alloc] init];
// 锁对象
ticketsCondition = [[NSCondition alloc] init];
ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[ticketsThreadone setName:@"Thread-1"];
[ticketsThreadone start];
ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[ticketsThreadtwo setName:@"Thread-2"];
[ticketsThreadtwo start];
NSThread *ticketsThreadthree = [[NSThread alloc] initWithTarget:self selector:@selector(run3) object:nil];
[ticketsThreadthree setName:@"Thread-3"];
[ticketsThreadthree start];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
-(void)run3{
while (YES) {
[ticketsCondition lock];
[NSThread sleepForTimeInterval:3];
[ticketsCondition signal];
[ticketsCondition unlock];
}
}
- (void)run{
while (TRUE) {
// 上锁
[ticketsCondition lock];
[ticketsCondition wait];
[theLock lock];
if(tickets >= 0){
[NSThread sleepForTimeInterval:0.09];
count = 100 - tickets;
NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]);
tickets--;
}else{
break;
}
[theLock unlock];
[ticketsCondition unlock];
}
}
wait是等待,我加了一个 线程3 去唤醒其余两个线程锁中的wait
咱们可使用指令 @synchronized 来简化 NSLock的使用,这样咱们就没必要显示编写建立NSLock,加锁并解锁相关代码。- (void)doSomeThing:(id)anObj{ @synchronized(anObj) { // Everything between the braces is protected by the @synchronized directive. }}