iOS开发多线程--线程状态

线程简介
  • 线程创建
self.thread=[[NSThread alloc]initWithTarget:self selector:@selector(test) object:nil];
// 线程有好几种创建方式,这里只写了一种创建方式
  • 线程的开启:
[self.thread start];
  • 线程的运行和阻塞:
    (1)设置线程阻塞1,阻塞2秒
    [NSThread sleepForTimeInterval:2.0];

(2)第二种设置线程阻塞2,以当前时间为基准阻塞4秒

    NSDate *date=[NSDate dateWithTimeIntervalSinceNow:4.0];
    [NSThread sleepUntilDate:date];

线程处理阻塞状态时在内存中的表现情况:(线程被移出可调度线程池,此时不可调度)

  • 线程的死亡:
    (1)当线程的任务结束,发生异常,或者是强制退出这三种情况会导致线程的死亡。
    (2)线程死亡后,线程对象从内存中移除。
代码示例
  • 线程阻塞
  #import "ViewController.h"
 @interface ViewController ()
 @property(nonatomic ,strong) NSThread * thread;
 @end
 @implementation ViewController
 - (void)viewDidLoad {
    [super viewDidLoad];
    // 创建线程
   self.thread = [[NSThread alloc]initWithTarget:self selector:@selector(therad) object:nil];
    // 设置线程名称
    self.thread.name = @"线程A";
  }
 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.thread start];
}
 -(void)therad
{
    //获取线程
    NSThread *current=[NSThread currentThread];
    NSLog(@"therad---打印线程---%@",self.thread.name);
    NSLog(@"therad---线程开始---%@",current.name);
    //设置线程阻塞1,阻塞2秒
    NSLog(@"接下来,线程阻塞2秒");
    [NSThread sleepForTimeInterval:2.0];
    //第二种设置线程阻塞2,以当前时间为基准阻塞4秒
    NSLog(@"接下来,线程阻塞4秒");
    NSDate *date=[NSDate dateWithTimeIntervalSinceNow:4.0];
    [NSThread sleepUntilDate:date];
      for (int i=0; i<10; i++) {
           NSLog(@"线程--%d--%@",i,current.name);
    }
   NSLog(@"test---线程结束---%@",current.name);
}
@end
  • 退出线程
  #import "ViewController.h"
 @interface ViewController ()
 @property(nonatomic ,strong) NSThread * thread;
 @end
 @implementation ViewController
 - (void)viewDidLoad {
    [super viewDidLoad];
    // 创建线程
   self.thread = [[NSThread alloc]initWithTarget:self selector:@selector(therad) object:nil];
    // 设置线程名称
    self.thread.name = @"线程A";
   }
 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.thread start];
}
 -(void)therad
{
    //获取线程
    NSThread *current=[NSThread currentThread];
    NSLog(@"therad---打印线程---%@",self.thread.name);
    NSLog(@"therad---线程开始---%@",current.name);
    //设置线程阻塞1,阻塞2秒
    NSLog(@"接下来,线程阻塞2秒");
    [NSThread sleepForTimeInterval:2.0];
    
    //第二种设置线程阻塞2,以当前时间为基准阻塞4秒
    NSLog(@"接下来,线程阻塞4秒");
    NSDate *date=[NSDate dateWithTimeIntervalSinceNow:4.0];
    [NSThread sleepUntilDate:date];
      for (int i=0; i<10; i++) {
           NSLog(@"线程--%d--%@",i,current.name);
          // 结束线程
          [NSThread exit];

    }
   NSLog(@"test---线程结束---%@",current.name);
}
@ end
注意:人死不能复生,线程死了也不能复生(重新开启),如果在线程死亡之后,再次点击屏幕尝试重新开启线程,则程序会挂。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容