NSThread浅析

来源:互联网 发布:市场调研软件 编辑:程序博客网 时间:2024/05/22 19:54

 NSThread是基于线程使用,轻量级的多线程编程方法(相对GCDNSOperation),一个NSThread对象代表一个线程,需要手动管理线程的生命周期,处理线程同步等问题

 

 NSThread常用方法介绍

 

 //动态创建

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

 [newThread start];

 

 //暂停一秒,当前是在主线程暂停一秒

 [NSThread sleepForTimeInterval:1.0];

 [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];

 

 //静态创建

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

 

 //线程取消

 [newThread cancel];

 

 //所有线程都停止

 [NSThread exit];

 

 //获取当前线程

 [NSThread currentThread];

 

 //获取主线程

 [NSThread mainThread];

 

 //给线程设置次高优先级

 [newThread setQualityOfService:NSQualityOfServiceUserInitiated];

 

 //指定当前线程执行操作

 [self performSelector:@selector(threadRun)];

 [self performSelector:@selector(threadRun) withObject:nil];

 [self performSelector:@selector(threadRun) withObject:nil afterDelay:2.0];

 

 //(在其他线程中)指定主线程执行操作

 [self performSelectorOnMainThread:@selector(threadRun) withObject:nil waitUntilDone:YES];

 

 //(在主线程中)指定其他线程执行操作

 [self performSelector:@selector(threadRun) onThread:newThread withObject:nil waitUntilDone:YES]; //这里指定为某个线程

 [self performSelectorInBackground:@selector(threadRun) withObject:nil];//这里指定为后台线程

 

 //线程同步 NSLock@synchronized

 

 

 方法是死的,用法是活的,且用且珍惜。。