在iOS开发中,多线程的实现方式主要有三种,NSThread、NSOperation和GCD,我前面博客中对NSOperation和GCD有了较为详细的实现,为了学习的完整性,今天我们主要从代码层面来实现NSThread的使用。案例代码上传至 https://github.com/chenyufeng1991/NSThread。
(1)初始化并启动一个线程
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
//获取当前线程
NSThread *current = [NSThread currentThread];
NSLog(@"当前线程为 %@",current);
//初始化线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
//设置线程的优先级(0.0-1.0)
thread.threadPriority = 1.0;
thread.name = @"新线程1";
[thread start];
}
- (void)run
{
NSLog(@"线程执行");
//获取当前线程
NSThread *current = [NSThread currentThread];
NSLog(@"当前线程为 %@",current);
//线程休眠,可以模拟耗时操作
[NSThread sleepForTimeInterval:2];
//获取主线程
NSThread *mainThread = [NSThread mainThread];
NSLog(@"子线程中获得主线程 %@",mainThread);
}
|
其中currentThread,这个方法很有用,常常可以用来判断某方法的执行是在哪个线程中。
(2)NSThread可以指定让某个线程在后台执行:
?| 1 2 3 |
//后台创建一个线程来执行任务,需要在调用的方法中使用自动释放池
[self performSelectorInBackground:@selector(run3) withObject:nil];
|
?
| 1 2 3 4 5 6 7 8 9 10 11 |
- (void)run3
{
@autoreleasepool {
NSLog(@"主线程3:%@,当前线程3:%@",[NSThread mainThread],[NSThread currentThread]);
}
}
|
(3)子线程执行耗时操作,主线程更新UI。这是多线程开发中最常用的案例。子线程中调用performSelectorOnMainThread方法用来更新主线程。
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
//测试在子线程中调用主线程更新UI
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSThread *subThread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
//NSThread可以控制线程开始
[subThread start];
}
- (void)run
{
NSLog(@"主线程1:%@,当前线程1:%@",[NSThread mainThread],[NSThread currentThread]);
//以下方法需要在子线程中调用
[self performSelectorOnMainThread:@selector(invocationMainThread) withObject:nil waitUntilDone:YES];
}
- (void)invocationMainThread
{
NSLog(@"主线程2:%@,当前线程2:%@",[NSThread mainThread],[NSThread currentThread]);
NSLog(@"调用主线程更新UI");
}
|
(4)同样,我们也可以新建一个子线程的类,继承自NSThread. 然后重写里面的main方法,main方法就是该线程启动时会执行的方法。
?
| 1 2 3 4 5 6 7 8 |
@implementation MyThread
- (void)main
{
NSLog(@"main方法执行");
}
@end
|
然后按正常的创建启动即可。线程就会自动去执行main方法。
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
//可以自己写一个子类,继承自NSThread,需要重写main方法
/**
* 执行的代码是在main中的,而不是使用@selector.
使用main方法,线程中执行的方法是属于对象本身的,这样可以在任何其他需要使用这个线程方法的地方使用,而不用再一次实现某个方法。
而其他的直接NSThread的创建线程,线程内执行的方法都是在当前的类文件里面的。
*/
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
MyThread *thread = [[MyThread alloc] init];
[thread start];
}
|
(5)NSThread中还有一个很常用的方法就是延迟。延迟2s执行。
?| 1 2 |
//线程休眠,可以模拟耗时操作
[NSThread sleepForTimeInterval:2];
|
对于多线程的三种实现方式,我们都要能够熟练使用








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。