iOS多线程之NSThread

什么是NSThread

NSThread是一种轻量级多线程,一个NSThread对象代表一个线程,需要手动管理线程的生命周期,处理线程同步。

NSThread的使用

1、线程创建

//创建方式1
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadMethod1) object:@"thread"];
[thread start];//该方式创建线程需要手动开启

//创建方式2
[NSThread detachNewThreadSelector:@selector(threadMethod2) toTarget:self withObject:@"detach"];

//创建方式3
 [NSThread detachNewThreadWithBlock:^{
        NSLog(@"thread==%@",[NSThread currentThread]);
  }];

2、线程的开启

针对上述第一种创建线程方式需要手动开启线程

[thread start];

3、线程的休眠

+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;

示例:线程休眠1秒

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

4、线程的取消

- (void)cancel API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));

示例:

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadMethod1) object:@"thread"];
[thread start];
[thread cancel];

5、线程的退出

+ (void)exit;

示例:

 [NSThread exit];

6、获取当前线程

[NSThread currentThread];

7、获取主线程

[NSThread currentThread];

8、线程属性

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadMethod1) object:@"thread"];
//name线程名称,在大型项目中使用该属性有助于开发调试,快速定位
thread.name = @"demoThread";

//threadPriority线程优先级0~1,保证cpu调度可能性的大小,0低,1高,在iOS8以后苹果不推荐使用,iOS8 后苹果建议使用qualityOfService
thread.threadPriority = 1;//开发过程中不建议使用

//qualityOfService
thread.qualityOfService = NSOperationQueuePriorityVeryHigh;
//qualityOfService有以下值
typedef NS_ENUM(NSInteger, NSQualityOfService) {
    /* UserInteractive QoS is used for work directly involved in providing an interactive UI such as processing events or drawing to the screen. */
    NSQualityOfServiceUserInteractive = 0x21,//用户交互事件,优先级最高
    
    /* UserInitiated QoS is used for performing work that has been explicitly requested by the user and for which results must be immediately presented in order to allow for further user interaction.  For example, loading an email after a user has selected it in a message list. */
    NSQualityOfServiceUserInitiated = 0x19,//用户马上要处理的事件,优先级仅次于NSQualityOfServiceUserInteractive
    
    /* Utility QoS is used for performing work which the user is unlikely to be immediately waiting for the results.  This work may have been requested by the user or initiated automatically, does not prevent the user from further interaction, often operates at user-visible timescales and may have its progress indicated to the user by a non-modal progress indicator.  This work will run in an energy-efficient manner, in deference to higher QoS work when resources are constrained.  For example, periodic content updates or bulk file operations such as media import. */
    NSQualityOfServiceUtility = 0x11,//普通优先级
    
    /* Background QoS is used for work that is not user initiated or visible.  In general, a user is unaware that this work is even happening and it will run in the most efficient manner while giving the most deference to higher QoS work.  For example, pre-fetching content, search indexing, backups, and syncing of data with external systems. */
    NSQualityOfServiceBackground = 0x09,//最低优先级

    /* Default QoS indicates the absence of QoS information.  Whenever possible QoS information will be inferred from other sources.  If such inference is not possible, a QoS between UserInitiated and Utility will be used. */
    NSQualityOfServiceDefault = -1//默认优先级,当用户没有设置线程优先级时默认为该优先级
} API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0));

9、线程间通信

- (id)performSelector:(SEL)aSelector;
- (id)performSelector:(SEL)aSelector withObject:(id)object;
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
- (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay;
- (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray *)modes;

//示例
[self performSelector:@selector(test)];
[self performSelector:@selector(test) withObject:nil];
[self performSelector:@selector(test) withObject:nil withObject:nil];
[self performSelector:@selector(test) withObject:nil afterDelay:1.0];
[self performSelector:@selector(test) withObject:nil afterDelay:1.0 inModes:@[NSRunLoopCommonModes]];

//在其他线程指定住线程执行test任务
[self performSelectorOnMainThread:@selector(test) withObject:nil waitUntilDone:YES];
//指定在某个线程执行test任务
[self performSelector:@selector(test) onThread:newThread withObject:nil waitUntilDone:YES]; 
//指定在后台线程执行test任务
[self performSelectorInBackground:@selector(test) withObject:nil];

你可能感兴趣的:(iOS多线程之NSThread)