多线程

单线程:

  • 每个正在运行的程序,至少包含一个线程,这个线程叫做主线程;
  • 主线程在程序启动时被创建,用于执行main函数
  • 只有一个主线程的程序被称为单线程程序
  • 在单线程程序中,代码只能顺序执行,无法并发执行

多线程:

  • 拥有多个线程的程序,称为多线程
  • iOS允许用户自己开辟新的线程,相对于主线程来说.这些线程,称为子线程
  • 可以根据需要开辟若干了子线程;
  • 子线程和主线程都是独立的运行单元,各自的执行互不影响;因此能够并执行

优缺点:

  • 单线程:只有一个线程.即主线程,代码顺序执行,容易出现代码阻塞(页面假死);
  • 多线程:有多个线程,线程间独立运行,能有效的避免代码阻塞,并且能提高程序的运行性能;
  • ios中关于UI的添加和刷新必须在主线程中操作

NSThread:

第一种方式:手动创建

    参数1:target
    参数2;方法
    参数3:传参
    创建对象
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(sayHi) object:nil];
    让线程开启
    [thread start];
    使用NSThread和NSObject实现的开辟线程,系统会议自动释放,
    结束线程的两种方式
    第一种:取消线程
    [thread cancel];//不是真的取消,而是给线程发送一个信号,通过信号取消
    第二种:直接将线程退出
    [NSThread exit];

第二种方式:自动创建

[NSThread detachNewThreadSelector:@selector(sayHi) toTarget:self withObject:nil;

NSObject:

    使用performSelectorInBackground开辟子线程
    参数1:selector
    参数2:方法传递的参数
    [self performSelectorInBackground:@selector(sayHi) withObject:@"qweqw"];
    self.view.backgroundColor = [UIColor orangeColor];

//子线程实现方法
- (void)sayHi{
    /*
    NSLog(@"hello,girl");

//打印当前线程的地址
    NSLog(@"current == %@",[NSThread currentThread]);

//打印主线程的地址
    NSLog(@"main == %@",[NSThread mainThread]);
     */
    //回到主线程,修改当前的颜色
    //参数1:selectar
    //参数2:传的参数
    //参数3:是否等待子线程完成之后进行主线程
    [self performSelectorOnMainThread:@selector(mainThreadChangColor) withObject:nil waitUntilDone:YES];


//主线程实现方法(处理UI要回到主线程)
- (void)mainThreadChangColor{
    self.view.backgroundColor = [UIColor redColor];
    NSLog(@"current == %@",[NSThread currentThread]);
    NSLog(@"main = %@",[NSThread mainThread]);
}

NSOperation    

//创建子线程
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(test) object:nil];

//启动任务
[operation start];

    需要把上边的两个线程,放到操作队列里边
    addoperation一旦创建的对象加入到操作队列中,就不能调用start方法    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
   [queue addOperation:operation];
    [queue addOperation:blockoperation];

GCD

使用GCD创建一个串行队列

   //第一种;系统提供的方法创建串行队列
    //dispatch_queue_t queue = dispatch_get_main_queue();//在真正的开发中如果需要创建串行队列,比较习惯用这种;
    //第二种方式:自己去创建
    //参数1:系统提供的一个宏,
    //参数2:系统的保留字段
    //参数1和参数2可以互换位置,先写什么都型
    //dispatch_queue_t queue = dispatch_queue_create(DISPATCH_QUEUE_SERIAL, 0);

使用GCD关键并行队列

   //第一种:系统的
    //参数1:优先级(有四个,没有明显区别)
    //参数2:系统保留字
    //dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
    
    //第二种:自己创建
    //参数1:表示创建队列的名字
    //参数2:系统提供的宏
    /*
    dispatch_queue_t queue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_CONCURRENT);
    //根据队列创建子线程
    dispatch_async(queue, ^{
        NSLog(@"current1 == %@,mainThread == %@",[NSThread currentThread],[NSThread mainThread]);
    });

原文地址:https://www.cnblogs.com/zhanglida/p/5503283.html