线程安全(互斥锁)-7

多线程的安全隐患

资源共享

1块资源可能会被多个线程共享,也就是多个线程可能会访问同一块资源

比如多个线程访问同一个对象、同一个变量、同一个文件

当多个线程访问同一块资源时,很容易影响数据错乱和数据安全问题

解决方法


互斥锁使用格式

@synchronized(所对象){

//需要锁定的代码

注意:锁定1份代码只用1把锁,用多把锁是无效的

互斥锁的优缺点:

优点:能有效防止因多线程抢夺资源造成的数据安全问题

缺点;需要消耗大量的CPU资源

互斥锁的使用前提:多条线程抢夺同一块资源

专业术语:线程同步

线程同步:多线程在同一条线上执行(按顺序地执行任务)

互斥锁,就是使用了线程同步的技术


}



@property (nonatomic, strong) NSThread *thread1;

@property (nonatomic, strong) NSThread *thread2;

@property (nonatomic, strong) NSThread *thread3;

@property (nonatomic, assign) NSInger ticketCount;

@property (nonatomic,strong) NSOject *locker;

- (void)viewDidLoad{

[super viewDidLoad];

self.ticketCount = 100;

self.locker = [[NSObject alloc]init];

self.thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];

self.thread1.name = @"售票员1";

self.thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];

self.thread2.name = @"售票员2";

self.thread3 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];

self.thread3.name = @"售票员3";

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

[slef.thread1 start];

[self.thread2 start];

[self.thread3 start];

}

 - (void)saleTicket{

@synchronized(self){

while(1){

//先取出票

NSInteger count = self.ticketCount;

if(count > 0){

self.ticketCount = count - 1;

NSLog(@"%@买了一张票,还剩下%ld张",[NSThread currentThread].name,self.ticketCount);

}else{

NSLog(@"票已经卖完了");

break;0

}

}

}

}


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 目录: (一)线程与进程之间的区别 (二)为什么需要学习多线程 (三)多线程任务执行方式 (四)多线程执行的...
    KingLionsFrank阅读 805评论 6 6
  • 一、多线程基础 基本概念 进程进程是指在系统中正在运行的一个应用程序每个进程之间是独立的,每个进程均运行在其专用且...
    AlanGe阅读 557评论 0 0
  • 原文地址 http://www.cnblogs.com/kenshincui/p/3983982.html 大家都...
    怎样m阅读 1,302评论 0 1
  • 说到多线程就不得不提多线程中的锁机制,多线程操作过程中往往多个线程是并发执行的,同一个资源可能被多个线程同时访问,...
    周末年安阅读 3,527评论 3 51
  • 今日收到一封学生的来信,询问如何写好英文论文的摘要。 想起初学写英文论文的时候,往往不知如何下手。经常是写了一句,...
    鸭梨山大哎阅读 672评论 0 2