当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS多线程开发——NSThread浅析

iOS多线程开发——NSThread浅析

2019年07月24日  | 移动技术网IT编程  | 我要评论

附庸风雅反义词,丁香花园果果秀,评选投票

  在ios开发中,多线程的实现方式主要有三种,nsthread、nsoperation和gcd,我前面博客中对nsoperation和gcd有了较为详细的实现,为了学习的完整性,今天我们主要从代码层面来实现nsthread的使用。案例代码上传至 https://github.com/chenyufeng1991/nsthread。

(1)初始化并启动一个线程

  - (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可以指定让某个线程在后台执行:


  //后台创建一个线程来执行任务,需要在调用的方法中使用自动释放池

  [self performselectorinbackground:@selector(run3) withobject:nil];

  - (void)run3

  {

  @autoreleasepool {

  nslog(@"主线程3:%@,当前线程3:%@",[nsthread mainthread],[nsthread currentthread]);

  }

  }

(3)子线程执行耗时操作,主线程更新ui。这是多线程开发中最常用的案例。子线程中调用performselectoronmainthread方法用来更新主线程。

//测试在子线程中调用主线程更新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方法就是该线程启动时会执行的方法。

@implementation mythread

- (void)main
{
 nslog(@"main方法执行");
}

@end

  然后按正常的创建启动即可。线程就会自动去执行main方法。

//可以自己写一个子类,继承自nsthread,需要重写main方法
/**
 * 执行的代码是在main中的,而不是使用@selector.
 使用main方法,线程中执行的方法是属于对象本身的,这样可以在任何其他需要使用这个线程方法的地方使用,而不用再一次实现某个方法。
 
 而其他的直接nsthread的创建线程,线程内执行的方法都是在当前的类文件里面的。
 */
- (void)viewwillappear:(bool)animated
{
 [super viewwillappear:animated];

 mythread *thread = [[mythread alloc] init];
 [thread start];
}

  (5)nsthread中还有一个很常用的方法就是延迟。延迟2s执行。

 //线程休眠,可以模拟耗时操作
 [nsthread sleepfortimeinterval:2];

   对于多线程的三种实现方式,我们都要能够熟练使用

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网