多线程(一) -NSThread

1.每个应用程序至少有一个主线程,它的主要工作是:更新显示UI界面、处理用户的触摸事件等;如果需要执行太耗时的操作,就需要用到多线程,多线程按抽象程度从低到高依次为:Thread,Cocoa Operations,GCD(ios4).


2.NSThread的初始化方法有三种:①动态方法:- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;

例如:

// 初始化线程

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

// 设置线程的优先级(0.0 - 1.0,1.0最高级)

thread.threadPriority =1;

// 开启线程

[thread start];

②静态方法:+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;

例如:

[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];

// 调用完毕后,会马上创建并开启新线程

③隐式创建:[self performSelectorInBackground:@selector(run) withObject:nil].


3.获取当前线程:NSThread *current = [NSThread currentThread];

获取主线程:NSThread *main = [NSThread mainThread];

暂停当前线程:①  [NSThread sleepForTimeInterval:2] 

②   NSDate *date = [NSDate dateWithTimeInterval:2.0f sinceDate:[NSDate date]];

      [NSThread sleepUntilDate:date];


4.线程间的通信:

①  在指定线程上执行操作: [self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];

②  在主线程上执行操作:  [self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];

③  在当前线程执行操作:[self performSelector:@selector(run) withObject:nil];


5.优缺点:

①  优点:NSThread比其他两种多线程方案较轻量级,更直观地控制线程对象。

②  缺点:需要自己管理线程的生命周期,线程同步。线程同步对数据的加锁会有一定的系统开销。

你可能感兴趣的:(多线程(一) -NSThread)