2023-05-12 开启多语言插件支持……

多线程编程-NSThread

ios 苏 demo 2991℃ 0评论

前言

每个iOS应用程序都有个专门用来更新显示UI界面、处理用户触摸事件的主线程,因此不能将其他太耗时的操作放在主线程中执行,不然会造成主线程堵塞(出现卡机现象),带来极坏的用户体验。一般的解决方案就是将那些耗时的操作放到另外一个线程中去执行,多线程编程是防止主线程堵塞,增加运行效率的最佳方法。

iOS中有3种常见的多线程编程方法:

1.NSThread

这种方法需要管理线程的生命周期、同步、加锁问题,会导致一定的性能开销

2.NSOperation和NSOperationQueue

是基于OC实现的。NSOperation以面向对象的方式封装了需要执行的操作,然后可以将这个操作放到一个NSOperationQueue中去异步执行。不必关心线程管理、同步等问题。

3.Grand Centeral Dispatch

简称GCD,iOS4才开始支持,是纯C语言的API。自iPad2开始,苹果设备开始有了双核CPU,为了充分利用这2个核,GCD提供了一些新特性来支持多核并行编程

这篇文章简单介绍NSThread这个类,一个NSThread实例就代表着一条线程

一、获取当前线程

1
NSThread *current = [NSThread currentThread];

二、获取主线程

1
2
NSThread *main = [NSThread mainThread];
NSLog(@"主线程:%@", main);

打印结果是:

1
2013-04-18 21:36:38.599 thread[7499:c07] 主线程:<NSThread: 0x71434e0>{name = (null), num = 1}

num相当于线程的id,主线程的num是为1的

三、NSThread的创建

1.动态方法

1
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;

在第2行创建了一条新线程,然后在第4行调用start方法启动线程,线程启动后会调用self的run:方法,并且将@”skywalkerwei”作为方法参数

1
2
3
4
// 初始化线程
 NSThread *thread = [[[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"skywalkerwei"] autorelease];
 // 开启线程
 [thread start];

假如run:方法是这样的:

1
2
3
4
- (void)run:(NSString *)string {
     NSThread *current = [NSThread currentThread];
     NSLog(@"执行了run:方法-参数:%@,当前线程:%@", string, current);
 }

打印结果为:

1
2013-04-18 21:40:33.102 thread[7542:3e13] 执行了run:方法-参数:mj,当前线程:<NSThread: 0x889e8d0>{name = (null), num = 3}

可以发现,这条线程的num值为3,说明不是主线程,主线程的num为1

2.静态方法

1
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;
1
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"skywalkerwei"];

执行完上面代码后会马上启动一条新线程,并且在这条线程上调用self的run:方法,以@”skywalkerwei”为方法参数

3.隐式创建线程

1
[self performSelectorInBackground:@selector(run:) withObject:@"skywalkerwei"];

会隐式地创建一条新线程,并且在这条线程上调用self的run:方法,以@”skywalkerwei”为方法参数

四、暂停当前线程

1
NSThread sleepForTimeInterval:2];
1
2
NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]]; 
[NSThread sleepUntilDate:date];

上面两种做法都是暂停当前线程2秒

五、线程的其他操作

1.在指定线程上执行操作

1
[self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];

2.在主线程上执行操作

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

3.在当前线程执行操作

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

六、优缺点

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

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

打赏

转载请注明:苏demo的别样人生 » 多线程编程-NSThread

   如果本篇文章对您有帮助,欢迎向博主进行赞助,赞助时请写上您的用户名。
支付宝直接捐助帐号oracle_lee@qq.com 感谢支持!
喜欢 (0)or分享 (0)