NSThread 的卖票(加锁) Demo
2015-12-03 19:41
381 查看
- (void)viewDidLoad { [super viewDidLoad]; _count = 50; //创建锁 _lock = [[NSLock alloc]init]; //主线程 NSLog(@"主线程%@",[NSThread currentThread]); //创建线程 [NSThread detachNewThreadSelector:@selector(sellTickets) toTarget:self withObject:nil]; [NSThread detachNewThreadSelector:@selector(sellTickets) toTarget:self withObject:nil]; [NSThread detachNewThreadSelector:@selector(sellTickets) toTarget:self withObject:nil]; [NSThread detachNewThreadSelector:@selector(sellTickets) toTarget:self withObject:nil]; } -(void) sellTickets{ /* while (_count>3) { [_lock lock]; //加锁防止资源同时被两个以上线程占用 _count--; NSLog(@"%@--票数:%ld",[NSThread currentThread],_count); [_lock unlock]; } */ //第二种 while (_count>0) { @synchronized(self){ //加锁防止资源同时被两个以上线程占用 [NSThread sleepForTimeInterval:0.2]; if (_count>0) { _count--; NSLog(@"%@--票数:%ld",[NSThread currentThread],_count); } } } }
相关文章推荐
- final
- 1033. To Fill or Not to Fill (25)【贪心+模拟】——PAT (Advanced Level) Practise
- hdu 1263 水果
- C plus plus(2)---using命名空间
- ubuntu下opencv + qt 开发环境的搭建
- rdm代码网址
- stackoverflow上SegFault对System.out.flush()的解释
- 实用windows命令集锦
- 同步刷新时对菜单格式的js点击增加class
- jquery动态调整表格宽度
- Local declaration of 'XXX' hides instance variable
- UI通讯录
- STM32f407驱动hc-sr04超声波测距模块
- 浅谈Java中的Set、List、Map的区别
- 根文件系统制作
- C#语法基础巩固
- 单点登录【转】
- JAVA框架——Maven
- 单例模式两种创建方法详解
- 正确的JQuery.ajax写法