赞
踩
一、如果多个子线程同时修改/更新同一个变量的值,造成数据不一致现象。
[Demo01_SellTicket]
分析问题: 多个子线程同时修改同一个值
解决方案: 适当的时候“加锁”;适当的时候“解锁”
- <span style="font-size:14px;"><span style="font-size:14px;">@interface ViewController ()
-
- /**剩余的票数*/
- @property (nonatomic, assign) int leftTicketCount;
- /**声明互斥锁的属性*/
- @property (nonatomic, strong) NSLock *lock;
-
- @end
-
- @implementation ViewController
-
- - (void)viewDidLoad {
- [super viewDidLoad];
- // 初始化lock对象
- self.lock = [[NSLock alloc] init];
- // 给定北京->深圳总票数
- NSNumber *totalTicketCount = @60;
- self.leftTicketCount = [totalTicketCount intValue];
-
- // 1.创建两个NSThread对象
-
- NSThread *firstThreadWindow = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket:) object:totalTicketCount];
- firstThreadWindow.name = @"窗口一";
- NSThread *secondThreadWindow = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket:) object:totalTicketCount];
- secondThreadWindow.name = @"窗口二";
- // 2.在子线程执行卖票逻辑
- // 3.启动卖票动作
- [firstThreadWindow start];
- [secondThreadWindow start];
-
- }
-
- - (void)sellTicket:(NSNumber *)totalCount {
- //下面的所有逻辑在子线程中执行整个卖票
- while (1) {
- //加锁
- [self.lock lock];
- if (self.leftTicketCount > 0) {
- //模拟延时操作(找个零钱...)
- [NSThread sleepForTimeInterval:0.1];
- //还有的卖
- self.leftTicketCount--;
- NSLog(@"窗口:%@;剩余票数:%d", [NSThread currentThread], self.leftTicketCount);
- //解锁
- [self.lock unlock];
- }else{
- //卖完了
- NSLog(@"票已经全部卖完了");
- //解锁
- [self.lock unlock];
- break;
- }
- }
- }</span></span>
1. 最好不要使用加锁 / 解锁,一般情况让服务器端做
2. 很少使用pthread / NSThread具体创建线程
3. [NSThread currentThread]: number=<?> name=<?>
4. 创建NSThread对象
a. 方式二: 调用形式相对简单
-》 创建子线程,并且同时执行sellTicket方法
[NSThread detachNewThreadSelector:@selector(sellTicket:) toTarget:self withObject:nil];
b. 方式一: 灵活性相对较高(适当的时候调用start)
NSThread *firstThreadWindow = [[NSThreadalloc]initWithTarget:selfselector:@selector(sellTicket:)object:totalTicketCount];
[firstThreadWindow start];
5. threadPriority: 线程优先级; 取值范围为:[0, 1];值越大, CPU调度的几率提高
二、GCD
- <span style="font-size:14px;"></pre><span style="color: rgb(51, 51, 51); font-family: arial, 宋体, sans-serif; line-height: 24px; text-indent: 28px;"><span style="font-size:14px;">Grand Central Dispatch (GCD)是Apple开发的一个多核编程的较新的解决方法。它主要用于优化应用程序以支持多核处理器以及其他对称多处理系统。它是一个在线程池模式的基础上执行的并行任务。</span></span></p><p class="p1"><div style="text-indent: 28px;"><span style="font-family:arial, 宋体, sans-serif;font-size:14px;color:#333333;"><span style="line-height: 24px;"></span></span><p class="p1"><span class="s1">1. 如何使用?</span></p><p class="p1"><span class="s1">1.0 一般的GCD的执行任务的流程</span></p><p class="p1"><span class="s1"> a. 创建队列</span></p><p class="p1"><span class="s1"> b. 给定任务,放到队列中</span></p><p class="p1"><span class="s1"> c. 执行队列中的任务</span></p><p class="p1"><span class="s1">1.1 队列类型</span></p><p class="p1"><span class="s1"> 串行队列(Serial Queue): </span><span class="s2">顺序</span><span class="s1">地执行</span></p><p class="p1"><span class="s1"> 并行队列(Concurrent Queue): </span><span class="s2">同时</span><span class="s1">地执行</span></p><p class="p1"><span class="s1"> 系统默认创建主队列(Main Queue): </span><span class="s2">主线程顺序</span><span class="s1">地执行</span></p><p class="p1"><span class="s1"> -》由主线程执行的串行队列</span></p><p class="p1"><span class="s1"> 系统默认创建全局队列(Global Queue):</span><span class="s2">同时</span><span class="s1">地执行</span></p><p class="p1"><span class="s1"> -》已经创建好的并行队列</span></p><p class="p1"><span class="s1">1.2 执行任务的方式</span></p><p class="p1"><span class="s1"> 同步执行(Sync): 当前线程 + 等待任务执行完毕</span></p><p class="p1"><span class="s1"> 异步执行(Async): 子线程 + 立即返回(不等待任务)</span></p><p class="p1"><span class="s1">1.3 明确知道两点:</span></p><p class="p1"><span class="s1"> a. 任务的执行顺序: 打印log,看时间</span></p><p class="p1"><span class="s1"> b. 有谁执行任务(主线程还是子线程):[NSThread currentThread]</span></p><p class="p1"><span class="s1">3.4 从多个排列组合中,寻找可以完成需求的组合</span></p><p class="p1"><span class="s1"> -> 子线程同时执行多个任务的组合</span></p><p class="p2"><span class="s3"> </span><span class="s2">a. </span><span class="s1">并行队列异步执行</span></p><p class="p2"><span class="s1"> b. 全局队列异步执行 (更常用)</span></p><p class="p1"><span class="s1"> -> 回到主线程的组合</span></p><p class="p1"><span class="s1"> </span><span class="s4">主队列异步执行</span></p></div><pre name="code" class="objc"><span style="font-size:14px;">- (void)viewDidLoad {
- [super viewDidLoad];
- // 正确认识"当前线程"
- dispatch_queue_t queue = dispatch_queue_create("ThirdConcurrentQueue", DISPATCH_QUEUE_CONCURRENT);
- dispatch_async(queue, ^{
- NSLog(@"并行队列异步执行开始%@", [NSThread currentThread]);
- //在同步执行任务
- //当前线程为子线程
- dispatch_sync(queue, ^{
- NSLog(@"xxxxx:%@", [NSThread currentThread]);
- });
- });
- }
-
- /**串行队列同步执行*/
- - (IBAction)serialQueueSync:(id)sender {
- /*明确点:任务的执行顺序; 主线程还是子线程执行
- 串行队列: 顺序地执行
- 同步执行: 当前线程 + 等待任务执行完毕
- */
- //1.创建串行队列(给定名字+指定队列类型)
- NSLog(@"开始执行啦:%@", [NSThread currentThread]);
- dispatch_queue_t queue = dispatch_queue_create("FirstSerialQueue", DISPATCH_QUEUE_SERIAL);
- //2.添加两个任务到串行队列中(block)
- //3.同步执行两个任务
- dispatch_sync(queue, ^{
- //添加第一个任务(耗时操作)
- for(int i = 0; i < 5; i++){
- [NSThread sleepForTimeInterval:1];
- NSLog(@"+++++++%@", [NSThread currentThread]);
- }
- });
- NSLog(@"打印+结束");
-
- dispatch_sync(queue, ^{
- for (int i = 0; i < 5; i++) {
- [NSThread sleepForTimeInterval:1];
- NSLog(@"--------%@", [NSThread currentThread]);
- }
- });
- NSLog(@"打印-结束");
- }
-
- /**串行队列异步执行*/
- - (IBAction)serialQueueAsync:(id)sender {
- /*
- 串行队列:顺序地执行
- 异步执行:当前线程 + 等待任务执行完毕
- */
- dispatch_queue_t queue = dispatch_queue_create("SecondSerialQueue", DISPATCH_QUEUE_SERIAL);
- dispatch_async(queue, ^{
- //添加到队列中的任务
- for (int i = 0; i < 5; i++) {
- [NSThread sleepForTimeInterval:1];
- NSLog(@"++++++%@", [NSThread currentThread]);
- }
- });
- NSLog(@"打印+完毕");
- dispatch_async(queue, ^{
- for (int i = 0; i < 5; i++) {
- [NSThread sleepForTimeInterval:1];
- NSLog(@"-------%@", [NSThread currentThread]);
- }
- });
- NSLog(@"打印-完毕");
- }
-
- /**并行队列同步执行*/
- - (IBAction)concurrentQueueSync:(id)sender {
- /*
- 并行队列:同时地执行
- 同步执行:当前线程 + 等待任务执行完毕
- */
- dispatch_queue_t queue = dispatch_queue_create("FirstConcurrentQueue", DISPATCH_QUEUE_CONCURRENT);
- dispatch_sync(queue, ^{
- for (int i = 0; i < 5; i++) {
- [NSThread sleepForTimeInterval:1];
- NSLog(@"+++++++%@", [NSThread currentThread]);
- }
- });
- NSLog(@"打印+完毕");
-
- dispatch_sync(queue, ^{
- for (int i = 0; i < 5; i++) {
- [NSThread sleepForTimeInterval:1];
- NSLog(@"-------%@", [NSThread currentThread]);
- }
- });
- NSLog(@"打印-完毕");
- }
-
- /**并行队列异步执行*/
- - (IBAction)concurrentQueueAsync:(id)sender {
- /*
- 并行队列:同时地执行
- 异步执行:子线程 + 立即返回(不等待任务)
- */
- dispatch_queue_t queue = dispatch_queue_create("SecondConcurrentQueue", DISPATCH_QUEUE_CONCURRENT);
- dispatch_async(queue, ^{
- for (int i = 0; i < 5; i++) {
- [NSThread sleepForTimeInterval:1];
- NSLog(@"+++++++%@", [NSThread currentThread]);
- }
- });
- NSLog(@"打印+完毕");
-
- dispatch_async(queue, ^{
- for (int i = 0; i < 5; i++) {
- [NSThread sleepForTimeInterval:1];
- NSLog(@"---------%@", [NSThread currentThread]);
- }
- });
- NSLog(@"打印-完毕");
- }
-
- /**全局队列异步执行*/
- - (IBAction)globalQueueAsync:(id)sender {
- //结论和并行队列异步执行一样
- //1.获取全局队列(只有这一步不一样)
- /*参数一:指定全局队列的优先级(主队列优先级最高)*/
- dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
- //2.添加任务
- dispatch_async(queue, ^{
- NSLog(@"+++++++%@", [NSThread currentThread]);
- });
- //3.异步执行任务
- NSLog(@"打印+完毕");
- }
-
- /**主队列异步执行*/
- - (IBAction)mainQueueAsync:(id)sender {
- //1.获取主队列
- dispatch_queue_t queue = dispatch_get_main_queue();
- //2.添加到主队列
- dispatch_async(queue, ^{
- for (int i = 0; i < 5; i++) {
- [NSThread sleepForTimeInterval:1];
- NSLog(@"--------%@", [NSThread currentThread]);
- }
- });
- NSLog(@"打印-完毕");
- }
-
- /**主队列同步执行*/
- - (IBAction)mainQueueSync:(id)sender {
- // dispatch_queue_t queue = dispatch_get_main_queue();
- NSLog(@"任务一");
- dispatch_sync(dispatch_get_main_queue(), ^{
- NSLog(@"任务二");
- });
- NSLog(@"任务三");
- }
- </span></span>
分析:
不用的组合:
1. 并行队列同步执行
a. 前提:当前线程是主线程的时候,不会达到同时执行任务的目的
2.一般都不使用同步执行任务;原因是会阻塞当前线程
3.主队列同步执行(死锁)
GCD底层实现原理:
1. 底层维护一个线程池,自动从线程池中找空闲的子线程
2. 不需要创建子线程对象;
Demo03_GCD_DownloadImage
- <span style="font-size:14px;">- (IBAction)downloadImageByGCD:(id)sender {
-
- //选择组合:全局队列异步执行 -> 由子线程下载图片
- dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
- dispatch_async(globalQueue, ^{
-
- NSLog(@"开始下载图片:%@", [NSThread currentThread]);
- //NSString -> NSURL -> NSData -> UIImage
- NSString *imageStr = @"http://www.egouz.com/uploadfile/2015/0305/20150305103626911.jpg";
- NSURL *imageURL = [NSURL URLWithString:imageStr];
- //下载图片
- NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
- UIImage *image = [UIImage imageWithData:imageData];
-
- //从子线程回到主线程(方式二:常用)
- //组合:主队列异步执行
- dispatch_async(dispatch_get_main_queue(), ^{
- NSLog(@"回到主线程:%@", [NSThread currentThread]);
- //更新界面
- self.imageView.image = image;
- });
-
- NSLog(@"xxxxxxxx");
- });
-
- //主线程执行
- NSLog(@"下载图片。。。。。");
- }
- </span>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。