浅析iOS应用开发中线程间的通信与线程安全问题

2020-01-14 17:11:54于海丽

    //第二种方式
    //    [self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];

    //第三种方式
   [self.iconView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
}


//设置显示图片
//-(void)settingImage:(UIImage *)image
//{
//    self.iconView.image=image;
//}

@end

 

线程安全
 
一、多线程的安全隐患
资源共享
1块资源可能会被多个线程共享,也就是多个线程可能会访问同一块资源
比如多个线程访问同一个对象、同一个变量、同一个文件
当多个线程访问同一块资源时,很容易引发数据错乱和数据安全问题
示例一:

浅析iOS应用开发中线程间的通信与线程安全问题

示例二:

浅析iOS应用开发中线程间的通信与线程安全问题

问题代码:

复制代码
//
//  YYViewController.m
//  05-线程安全
//
//  Created by apple on 14-6-23.
//  Copyright (c) 2014年 itcase. All rights reserved.
//

 


#import "YYViewController.h"

@interface YYViewController ()
//剩余票数

@property(nonatomic,assign) int leftTicketsCount;
@property(nonatomic,strong)NSThread *thread1;
@property(nonatomic,strong)NSThread *thread2;
@property(nonatomic,strong)NSThread *thread3;