iOS 多线程学习总结

一、基本概念:(多线程是通过提高资源使用率来提高系统总体的效率)

  • 进程:
    可以理解成一个运行中的应用程序,是系统进行资源分配和调度的基本单位,是操作系统结构的基础,主要管理资源。
  • 线程:
    是进程的基本执行单元,一个进程对应多个线程。
  • 主线程:
    处理UI,所有更新UI的操作都必须在主线程上执行。不要把耗时操作放在主线程,界面会卡。
  • 多线程:
    在同一时刻,一个CPU只能处理1条线程,但CPU可以在多条线程之间快速的切换,只要切换的足够快,就造成了多线程一同执行的假象。
  • 目的:
    将耗时的操作放在后台执行

二、线程的状态与生命周期

线程的生命周期是:新建 - 就绪 - 运行 - 阻塞 - 死亡

  • 线程状态示意图


    图1

说明:

  • 新建:
    实例化线程对象
  • 就绪:
    向线程对象发送start消息,线程对象被加入可调度线程池等待CPU调度。
  • 运行:
    CPU 负责调度可调度线程池中线程的执行。线程执行完成之前,状态可能会在就绪和运行之间来回切换。就绪和运行之间的状态变化由CPU负责,程序员不能干预。
  • 阻塞:
    当满足某个预定条件时,可以使用休眠或锁,阻塞线程执行。sleepForTimeInterval(休眠指定时长),sleepUntilDate(休眠到指定日期),@synchronized(self):(互斥锁)。
  • 死亡:
    正常死亡,线程执行完毕。非正常死亡,当满足某个条件后,在线程内部中止执行/在主线程中止线程对象
  • [NSThread exit]:
    一旦强行终止线程,后续的所有代码都不会被执行。
  • [thread cancel]:
    并不会直接取消线程,只是给线程对象添加 isCancelled 标记。

三、多线程的四种解决方案

  • pthread
    一套通用的多线程API
    适用于 Unix / Linux / Windows 等系统
    跨平台/可移植
  • NSThread
    使用更加面向对象
    简单易用,可直接操作线程对象
  • GCD
    旨在替代 NSThread 等线程技术
    充分利用设备的多核
  • NSOperation
    基于GCD(底层是GCD)
    比GCD多了一些更简单实用的功能
    使用更加面向对象
方案 语言 线程生命周期 实用频率
pthread C语言 程序员管理 几乎不用
NSThread OC语言 程序员管理 偶尔使用
GCD C语言 自动管理 经常使用
NSOperation OC语言 自动管理 经常使用

四、线程安全问题

  • 原因:
    当多个线程访问同一块资源时,很容易引发数据错乱和数据安全问题。
  • 解决多线程安全问题的方法:
    方法一:互斥锁(同步锁)
@synchronized(锁对象) {
    //需要锁定的代码
}

加了互斥做的代码,当新线程访问时,如果发现其他线程正在执行锁定的代码,新线程就会进入休眠。

  • 注意:
    判断的时候锁对象要存在,如果代码中只有一个地方需要加锁,大多都使用self作为锁对象,这样可以避免单独再创建一个锁对象。
    锁对象切记不能是局部变量。
    方法二:自选锁
    加了自旋锁,当新线程访问代码时,如果发现有其他线程正在锁定代码,新线程会用死循环的方式,一直等待锁定的代码执行完成。相当于不停尝试执行代码,比较消耗性能。

  • 属性修饰nonatomic 和 atomic

nonatomic:非原子属性(非线程安全),同一时间可以有很多线程 读 和 写,效率高
atomic:原子属性(线程安全),保证同一时间只有一个线程能够写入(但是同一个时间多个线程都可以读值)
atomic:本身就有一把自旋锁,且只对 写 操作进行加锁,对 读 操作没有限制

五、NSThread的使用

  1. 三种创建方式:
  • initWithTarget / initWithBlock
    创建好后,需要通过 start 启动
  • detachNewThreadSelector / detachNewThreadWithBlock
    创建好之后自动启动
  • performSelectorInBackground
    创建好之后自动启动
//方法一
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:@"NSThread01"];
[thread start];

//方法二
[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:@"NSThread02"];

//方法三
[self performSelectorInBackground:@selector(doSomething:) withObject:@"NSThread03"];

- (void)doSomething:(NSString *) object_str
{
    NSLog(@"参数:%@, 线程:%@", object_str, [NSThread currentThread]);
}
  1. NSThread相关类方法
  • 返回当前线程
// 当前线程
[NSThread currentThread];
NSLog(@"%@", [NSThread currentThread]);
 
// 如果number=1,则表示在主线程,否则是子线程
打印结果:{number = 1, name = main}
  • 阻塞睡眠
//休眠多久
[NSThread sleepForTimeInterval:2];
//休眠到指定时间
[NSThread sleepUntilDate:[NSDate date]];
  • 其他
//退出线程
[NSThread exit];
//判断当前线程是否为主线程
[NSThread isMainThread];
//判断当前线程是否是多线程
[NSThread isMultiThreaded];
//主线程的对象
NSThread *mainThread = [NSThread mainThread];
  1. NSThread相关属性
//线程是否在执行
thread.isExecuting;
//线程是否被取消
thread.isCancelled;
//线程是否完成
thread.isFinished;
//是否是主线程
thread.isMainThread;
//线程的优先级,取值范围0.0到1.0,默认优先级0.5,1.0表示最高优先级,优先级高,CPU调度的频率高
 thread.threadPriority;

注意:线程优先级和线程执行顺序之间不是必然关系

六、 GCD(Grand Central Dispatch)

  1. Dispatch Queue(队列)
队列种类 说明
串行队列(DISPATCH_QUEUE_SERIAL) 按FIFO的顺序执行,一个任务执行完成才会执行下一个任务
并发队列(DISPATCH_QUEUE_CONCURRENT) 任务无序同时执行
执行方式 说明
同步执行 任务都在当前线程中执行,并且会阻塞当前线程
异步执行 任务会在开辟的新线程中执行,不会阻塞当前线程
组合方式 说明
串行同步队列 任务都在当前线程执行(同步),并且顺序执行(串行)
串行异步队列 任务都在开辟的新的子线程中执行(异步),并且顺序执行(串行)
并发同步队列 任务都在当前线程执行(同步),但是是顺序执行的(并发的特性并没有体现出来)
并发异步队列 任务在开辟的多个子线程中执行(异步),并且是同时执行的(并发)
  1. 创建队列:
/**
 串行队列:serial_queue1
 */
dispatch_queue_t serial_queue1 = dispatch_queue_create("com.seral.queue", DISPATCH_QUEUE_SERIAL);
    
/**
 串行队列:serial_queue2
 */
dispatch_queue_t serial_queue2 = dispatch_queue_create("com.seral.queue", NULL);
    
/**
 并发队列:concurrent_queue
 */
dispatch_queue_t concurrent_queue = dispatch_queue_create("com.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);
/**
 主队列(串行队列):main_queue
 */
dispatch_queue_t main_queue = dispatch_get_main_queue();
/**
 全局队列(并发队列):global_queue
 */
dispatch_queue_t global_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  1. 组合方式说明

(1) 串行同步队列

dispatch_queue_t serial_queue = dispatch_queue_create("com.serial.queue", NULL);

dispatch_sync(serial_queue, ^{
    NSLog(@"--- 1 --- %@ ---", [NSThread currentThread]);
});
dispatch_sync(serial_queue, ^{
    NSLog(@"--- 2 --- %@ ---", [NSThread currentThread]);
});
dispatch_sync(serial_queue, ^{
    NSLog(@"--- 3 --- %@ ---", [NSThread currentThread]);
});

结果:

--- 1 --- {number = 1, name = main} ---
--- 2 --- {number = 1, name = main} ---
--- 3 --- {number = 1, name = main} ---

(2) 串行异步队列

dispatch_queue_t serial_queue = dispatch_queue_create("com.serial.queue", NULL);

dispatch_async(serial_queue, ^{
    NSLog(@"--- 1 --- %@ ---", [NSThread currentThread]);
});
dispatch_async(serial_queue, ^{
    NSLog(@"--- 2 --- %@ ---", [NSThread currentThread]);
});
dispatch_async(serial_queue, ^{
    NSLog(@"--- 3 --- %@ ---", [NSThread currentThread]);
});

结果:

--- 1 --- {number = 3, name = (null)} ---
--- 2 --- {number = 3, name = (null)} ---
--- 3 --- {number = 3, name = (null)} ---

(3) 并发同步队列

dispatch_queue_t concurrent_queue = dispatch_queue_create("com.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);

dispatch_sync(concurrent_queue, ^{
    NSLog(@"--- 1 --- %@ ---", [NSThread currentThread]);
});
dispatch_sync(concurrent_queue, ^{
    NSLog(@"--- 2 --- %@ ---", [NSThread currentThread]);
});
dispatch_sync(concurrent_queue, ^{
    NSLog(@"--- 3 --- %@ ---", [NSThread currentThread]);
});

结果:

--- 1 --- {number = 1, name = main} ---
--- 2 --- {number = 1, name = main} ---
--- 3 --- {number = 1, name = main} ---

(4) 并发异步队列

dispatch_queue_t concurrent_queue = dispatch_queue_create("com.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(concurrent_queue, ^{
    NSLog(@"--- 1 --- %@ ---", [NSThread currentThread]);
});
dispatch_async(concurrent_queue, ^{
    NSLog(@"--- 2 --- %@ ---", [NSThread currentThread]);
});
dispatch_async(concurrent_queue, ^{
    NSLog(@"--- 3 --- %@ ---", [NSThread currentThread]);
});

结果:

--- 3 --- {number = 4, name = (null)} ---
--- 1 --- {number = 3, name = (null)} ---
--- 2 --- {number = 5, name = (null)} ---
  1. 队列组

作用:队列组是用来管理队列中任务的执行

dispatch_group_t group = dispatch_group_create();
dispatch_queue_t concurrent_queue = dispatch_queue_create("com.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);

dispatch_group_async(group, concurrent_queue, ^{
    NSLog(@"--- 1 --- %@ ---", [NSThread currentThread]);
});
dispatch_group_async(group, concurrent_queue, ^{
    NSLog(@"--- 2 --- %@ ---", [NSThread currentThread]);
});
dispatch_group_async(group, concurrent_queue, ^{
    NSLog(@"--- 3 --- %@ ---", [NSThread currentThread]);
});

dispatch_group_notify(group, concurrent_queue, ^{
    NSLog(@"到这里就结束了!");
});

结果:

--- 2 --- {number = 8, name = (null)} ---
--- 3 --- {number = 3, name = (null)} ---
--- 1 --- {number = 7, name = (null)} ---
  1. Barrier

(1) 通过 barrier 添加的 block ,会等其之前添加的所有 block 执行完毕再执行
(2) 在 barrier 之后添加的 block ,会等其添加的 block 执行完毕再执行
(3) 只在自定义创建的并发队列有效

dispatch_queue_t concurrent_queue = dispatch_queue_create("com.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(concurrent_queue, ^{
    NSLog(@"--- reading 1 --- %@ ---", [NSThread currentThread]);
});
dispatch_async(concurrent_queue, ^{
    NSLog(@"--- reading 2 --- %@ ---", [NSThread currentThread]);
});
dispatch_async(concurrent_queue, ^{
    NSLog(@"--- reading 3 --- %@ ---", [NSThread currentThread]);
});

/**
 此处使用 dispatch_barrier_sync,block任务在当前线程中执行
 */
dispatch_barrier_async(concurrent_queue, ^{
    NSLog(@"--- writing 0 --- %@ ---", [NSThread currentThread]);
});

dispatch_async(concurrent_queue, ^{
    NSLog(@"--- reading 4 --- %@ ---", [NSThread currentThread]);
});dispatch_async(concurrent_queue, ^{
    NSLog(@"--- reading 5 --- %@ ---", [NSThread currentThread]);
});dispatch_async(concurrent_queue, ^{
    NSLog(@"--- reading 6 --- %@ ---", [NSThread currentThread]);
});

结果:

--- reading 2 --- {number = 11, name = (null)} ---
--- reading 1 --- {number = 13, name = (null)} ---
--- reading 3 --- {number = 14, name = (null)} ---
--- writing 0 --- {number = 14, name = (null)} ---
--- reading 5 --- {number = 13, name = (null)} ---
--- reading 4 --- {number = 14, name = (null)} ---
--- reading 6 --- {number = 11, name = (null)} ---

全局队列中:

dispatch_queue_t global_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(global_queue, ^{
    NSLog(@"--- reading 1 --- %@ ---", [NSThread currentThread]);
});
dispatch_async(global_queue, ^{
    NSLog(@"--- reading 2 --- %@ ---", [NSThread currentThread]);
});
dispatch_async(global_queue, ^{
    NSLog(@"--- reading 3 --- %@ ---", [NSThread currentThread]);
});

dispatch_barrier_async(global_queue, ^{
    NSLog(@"--- writing 0 --- %@ ---", [NSThread currentThread]);
});

dispatch_async(global_queue, ^{
    NSLog(@"--- reading 4 --- %@ ---", [NSThread currentThread]);
});dispatch_async(global_queue, ^{
    NSLog(@"--- reading 5 --- %@ ---", [NSThread currentThread]);
});dispatch_async(global_queue, ^{
    NSLog(@"--- reading 6 --- %@ ---", [NSThread currentThread]);
});

结果:

--- reading 1 --- {number = 12, name = (null)} ---
--- reading 2 --- {number = 10, name = (null)} ---
--- writing 0 --- {number = 11, name = (null)} ---
--- reading 3 --- {number = 13, name = (null)} ---
--- reading 4 --- {number = 6, name = (null)} ---
--- reading 5 --- {number = 8, name = (null)} ---
--- reading 6 --- {number = 7, name = (null)} ---

串行队列中:

dispatch_queue_t serial_queue = dispatch_queue_create("com.serial.queue", NULL);

dispatch_async(serial_queue, ^{
    NSLog(@"--- reading 1 --- %@ ---", [NSThread currentThread]);
});
dispatch_async(serial_queue, ^{
    NSLog(@"--- reading 2 --- %@ ---", [NSThread currentThread]);
});
dispatch_async(serial_queue, ^{
    NSLog(@"--- reading 3 --- %@ ---", [NSThread currentThread]);
});

dispatch_barrier_async(serial_queue, ^{
    NSLog(@"--- writing 0 --- %@ ---", [NSThread currentThread]);
});

dispatch_async(serial_queue, ^{
    NSLog(@"--- reading 4 --- %@ ---", [NSThread currentThread]);
});dispatch_async(serial_queue, ^{
    NSLog(@"--- reading 5 --- %@ ---", [NSThread currentThread]);
});dispatch_async(serial_queue, ^{
    NSLog(@"--- reading 6 --- %@ ---", [NSThread currentThread]);
});

结果:

--- reading 1 --- {number = 4, name = (null)} ---
--- reading 2 --- {number = 4, name = (null)} ---
--- reading 3 --- {number = 4, name = (null)} ---
--- writing 0 --- {number = 4, name = (null)} ---
--- reading 4 --- {number = 4, name = (null)} ---
--- reading 5 --- {number = 4, name = (null)} ---
--- reading 6 --- {number = 4, name = (null)} ---
  1. Semaphore (信号量)
/**
 创建方法:初始值必须 >= 0
 */
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
/**
 等待一个信号
 DISPATCH_TIME_NOW :不等待
 DISPATCH_TIME_FOREVER :一直等待,直到收到信号
 返回 0 为成功,非 0 就是超时
 */
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
/**
 发送信号:信号量计数增加
 */
dispatch_semaphore_signal(semaphore);

实例1:多个网络请求并发执行

dispatch_queue_t global_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

dispatch_group_async(group, global_queue, ^{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_semaphore_signal(semaphore);
        NSLog(@"--- 请求 1 ---");
    });
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
});
dispatch_group_async(group, global_queue, ^{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_semaphore_signal(semaphore);
        NSLog(@"--- 请求 2 ---");
    });
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
});
dispatch_group_async(group, global_queue, ^{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_semaphore_signal(semaphore);
        NSLog(@"--- 请求 3 ---");
    });
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
});

dispatch_group_notify(group, global_queue, ^{
    NSLog(@"--- 请求全部完成! ---");
});

结果:

--- 请求 3 ---
--- 请求 2 ---
--- 请求 1 ---
--- 请求全部完成! ---

实例2:多个网络请求顺序执行

dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
dispatch_queue_t serial_queue = dispatch_queue_create("com.serial_queue", NULL);

dispatch_async(serial_queue, ^{
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"--- 请求 1 ---");
        dispatch_semaphore_signal(semaphore);

    });
});
dispatch_async(serial_queue, ^{
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"--- 请求 2 ---");
        dispatch_semaphore_signal(semaphore);

    });
});
dispatch_async(serial_queue, ^{
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"--- 请求 3 ---");
        dispatch_semaphore_signal(semaphore);
    });
});

结果:

--- 请求 1 ---
--- 请求 2 ---
--- 请求 3 ---

GitHub地址:Demo

你可能感兴趣的:(iOS 多线程学习总结)