IOS学习 多线程NSThread 共享变量 卖票
2016-03-28 23:59
399 查看
#import "ViewController.h"
@interface
ViewController ()
//火车票
@property (nonatomic,assign)
int tickets;
@property (nonatomic,strong)
NSObject *obj;
//nonatomic 非原子属性:多个线程可同时读取、赋值
//atomic 原子属性:多个线程下,只有一线程可对变量赋值,多个线程可同时读取
//自旋锁
@property (atomic,strong)
NSObject *obj2;
@end
@implementation ViewController
- (void)viewDidLoad {
[super
viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.tickets =
5;
self.obj = [[NSObject
alloc] init];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent
*)event{
NSThread *thread1 = [[NSThread
alloc]initWithTarget:self
selector:@selector(sellTicket)
object:nil];
[thread1 start];
NSThread *thread2 = [[NSThread
alloc]initWithTarget:self
selector:@selector(sellTicket)
object:nil];
[thread2 start];
}
- (void)sellTicket{
while (YES) {
//模拟网络延时
[NSThread
sleepForTimeInterval:1];
//锁是任意对象,默认锁是开着的
//同步锁(互斥锁)
自选锁不能代替同步锁
@synchronized(self) {
if (self.tickets >
0) {
_tickets -=
1;
NSLog(@"剩余
%d 张票",_tickets);
continue;
}
NSLog(@"票卖完了");
break;
}
}
}
@interface
ViewController ()
//火车票
@property (nonatomic,assign)
int tickets;
@property (nonatomic,strong)
NSObject *obj;
//nonatomic 非原子属性:多个线程可同时读取、赋值
//atomic 原子属性:多个线程下,只有一线程可对变量赋值,多个线程可同时读取
//自旋锁
@property (atomic,strong)
NSObject *obj2;
@end
@implementation ViewController
- (void)viewDidLoad {
[super
viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.tickets =
5;
self.obj = [[NSObject
alloc] init];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent
*)event{
NSThread *thread1 = [[NSThread
alloc]initWithTarget:self
selector:@selector(sellTicket)
object:nil];
[thread1 start];
NSThread *thread2 = [[NSThread
alloc]initWithTarget:self
selector:@selector(sellTicket)
object:nil];
[thread2 start];
}
- (void)sellTicket{
while (YES) {
//模拟网络延时
[NSThread
sleepForTimeInterval:1];
//锁是任意对象,默认锁是开着的
//同步锁(互斥锁)
自选锁不能代替同步锁
@synchronized(self) {
if (self.tickets >
0) {
_tickets -=
1;
NSLog(@"剩余
%d 张票",_tickets);
continue;
}
NSLog(@"票卖完了");
break;
}
}
}
相关文章推荐
- iOS: 聊聊 Designated Initializer(指定初始化函数)
- 第一篇还是自我介绍吧
- IOS 杂笔-17(堆区栈区等)
- iOS开发小技巧--cell往左拖拽出现很多按钮的实现,仅仅适用于iOS8以后
- ios学习 多线程NSThread 基本属性
- iOS 富文本属性
- iOS开源项目
- iOS开发之delegate设计模式
- Bios工程师手边事—PCI资源分配
- IOS开发之录音与播放功能
- OC阅读笔记五:异常机制
- iOS开发-单元测试
- IOS开发之单例
- iOS 中socket的总结
- ubuntu下重装WIN7
- iOS文件操作学习3-28
- 对关于iOS图片压缩的一点积累
- iOS - 开发小技巧
- IOS判断文件是否可读 可写 可执行
- iOS 九宫格的实现