NSThread浅析

 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

 

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Objective-C是一门面向对象的编程语言,它是C语言的扩展,常用于开发iOS和Mac应用程序。在Objective-C中,线程是用来执行并发任务的执行单元。 Objective-C中处理线程的方式有多种,最常用的方式是使用NSThread类或GCD(Grand Central Dispatch)。下面我将简单介绍这两种方式: 1. NSThreadNSThread是Objective-C封装的线程类,可以手动创建和管理线程。你可以通过创建NSThread对象,并调用start方法来启动线程。NSThread提供了一些方法,如sleep、exit、cancel等,用于线程的控制和管理。 示例代码: ``` NSThread *myThread = [[NSThread alloc] initWithTarget:self selector:@selector(myThreadMethod) object:nil]; [myThread start]; ``` 2. GCD(Grand Central Dispatch):GCD是一种更现代化的多线程编程方式,它提供了一种高效且易于使用的并发模型。GCD使用队列(dispatch queue)来管理任务的执行,分为串行队列和并发队列两种类型。 示例代码: ``` // 创建并发队列 dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // 在并发队列上异步执行任务 dispatch_async(concurrentQueue, ^{ // 执行任务的代码 }); ``` 以上是Objective-C中处理线程的两种常见方式,具体选择哪一种取决于你的需求和偏好。需要注意的是,在iOS开发中,为了确保UI的响应性,UI的更新必须在主线程(也称为主队列)上执行,可以使用GCD的主队列来实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值