iOS 线程安全小事例

#import"ViewController.h"

@interfaceViewController()

/**售票员A */

@property(nonatomic,strong)NSThread*threadA;

/**售票员B */

@property(nonatomic,strong)NSThread*threadB;

/**售票员C */

@property(nonatomic,strong)NSThread*threadC;

@property(nonatomic,assign)NSIntegertotalCount;

@end

@implementationViewController

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

{

//设置中票数

self.totalCount=100;

self.threadA= [[NSThreadalloc]initWithTarget:selfselector:@selector(saleTicket)object:nil];

self.threadB= [[NSThreadalloc]initWithTarget:selfselector:@selector(saleTicket)object:nil];

self.threadC= [[NSThreadalloc]initWithTarget:selfselector:@selector(saleTicket)object:nil];

self.threadA.name=@"售票员A";

self.threadB.name=@"售票员B";

self.threadC.name=@"售票员C";

//启动线程

@synchronized(self) {

[self.threadAstart];

[self.threadBstart];

[self.threadCstart];

}

-(void)saleTicket

{

while(1) {

//锁:必须是全局唯一的

//1.注意枷锁的位置

//2.注意枷锁的前提条件,多线程共享同一块资源

//3.注意加锁是需要代价的,需要耗费性能的

//4.加锁的结果:线程同步

@synchronized(self) {

//线程1

//线程2

//线程3

NSIntegercount =self.totalCount;

if(count >0) {

for(NSIntegeri =0; i<1000000; i++) {

}

self.totalCount= count -1;

//卖出去一张票

NSLog(@"%@卖出去了一张票,还剩下%zd张票", [NSThreadcurrentThread].name,self.totalCount);

}else

{

NSLog(@"卖完了");

break;

}

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

推荐阅读更多精彩内容

  • 一、多线程基础 基本概念 进程进程是指在系统中正在运行的一个应用程序每个进程之间是独立的,每个进程均运行在其专用且...
    AlanGe阅读 557评论 0 0
  • 目录: (一)线程与进程之间的区别 (二)为什么需要学习多线程 (三)多线程任务执行方式 (四)多线程执行的...
    KingLionsFrank阅读 791评论 6 6
  • 首先推荐一部电视剧 很早以前看过一部港剧《龙兄鼠弟》,是万梓良、郑则仕和张卫健演的。其中万梓良饰演的雷文凤,在最后...
    庄表伟阅读 13,583评论 2 14
  • 告诉自己爱你没错 可现实不断反驳我 翻开你的微博 看你对她那么在意,那么关心,那么温柔 或许是我该放手 可那么舍不...
    安安M阅读 170评论 0 0
  • 忘了有多长时间没有真正静下心来写自己的东西,确定地说,应该是高中毕业以后,是的,十年没有认真写下一篇文章了...
    侬小姐阅读 284评论 0 1