標籤:
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic,strong)NSThread *thread1;
@property(nonatomic,strong)NSThread *thread2;
@property(nonatomic,strong)NSThread *thread3;
//剩餘票
@property(nonatomic,assign)NSInteger leftTickets;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.leftTickets=100;//總票數
// 初始化三個賣票視窗
self.thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTickets:) object:@"1號視窗"];
self.thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTickets:) object:@"2號視窗"];
self.thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTickets:) object:@"3號視窗"];
}
-(void)touchesBegan:(NSSet *)touches withEvent:( UIEvent *)event
{
//開始買票
[self.thread1 start];
[self.thread2 start];
[self.thread3 start];
}
-(void)saleTickets:(NSString*)str
{
while (1) {
@synchronized(self) {
[NSThread sleepForTimeInterval:0.5];
if(self.leftTickets>0)
{
self.leftTickets--;
NSLog(@"餘票:%ld,買票的進程:%@",self.leftTickets,[NSThread currentThread]);
}
else
{
return;
}
}
}
}
iOS 線程間共用資源添加排它鎖