多线程:线程的安全问题
2016-03-24 14:22
197 查看
// // ViewController.m // 06-线程安全 // // Created by gzxzmac on 16/1/28. // Copyright © 2016年 gzxzmac. All rights reserved. // #import "ViewController.h" @interface ViewController () @property (nonatomic, assign) NSInteger ticket;// 总共的票数 @property (nonatomic, strong) NSObject *obj; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.obj = [[NSObject alloc]init]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { self.ticket = 20; // 创建线程卖票 NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil]; // 设置线程的名字 thread.name = @"售员01"; // 开始卖票 [thread start]; // // 创建线程卖票 NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil]; // 设置线程的名字 thread1.name = @"售员02"; // 开始卖票 [thread1 start]; } /* 1. 要做到卖出去的票是正确的,而且刚好卖完 2. 使用互斥锁可以解决线程共享资源问题 3. 互斥锁的作用:锁内的代码,在同一时间,只能在一个线程上执行 4. 互斥锁使用的资源会比较多,锁内的代码越少越好,锁住线程共享属性(变量)的setter 和 getter */ - (void)saleTicket { // 互斥锁 while (YES) { // 设置休眠 [NSThread sleepForTimeInterval:1.f]; // 锁对象 -> 所有的对象都可以.不要使用局部变量.一般情况下使用self // NSObject *obj = [[NSObject alloc]init]; @synchronized(self) { // 需要上锁的代码 // 判断是否有票 if (self.ticket > 0) { self.ticket --; NSLog(@"卖出一张票 %zd %@",self.ticket,[NSThread currentThread]); // 下一个 continue; } // 卖完之后才有可能执行 NSLog(@"卖完了"); break; // else {// 卖完了 // NSLog(@"卖完了"); // break; // } } } } @end
相关文章推荐
- lambda表达式
- 在POM中配置远程仓库
- oracle ceil和floor函数
- JAVA的代理模式(静态代理、JDK动态代理、cglib动态代理)
- rsync配置详细版
- eclipse debug问题
- (转)接口自动化测试 – Java+TestNG 测试 Restful Web Service
- 2016/3/24 ①数据库与php连接 三种输出fetch_row()、fetch_all()、fetch_assoc() ②增删改时判断(布尔型) ③表与表之间的联动 ④下拉菜单 ⑤登陆 三个页面
- Linux 内核的文件 Cache 管理机制介绍
- SCWS 中文分词
- CentOS 7 安装 SVN 服务
- js判断html页面是否滚动到了最底部
- 在浏览器中运行java applet
- Github安装入门及git的简单
- 持续集成篇_03_svn版本管理系统的使用(centos+subversion+apache+jsvnadmin+tortoisesvn)
- 多线程:线程的属性
- PowerDesigner 的mysql PDM 的COMMENT注释改为name+comment
- MySQL Binlog的介绍
- linux 技巧:使用 screen 管理你的远程会话
- 杂记