您的位置:首页 > 移动开发 > IOS开发

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;

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: