标签:
- (IBAction)action:(id)sender {
count=100;
self.thread1=[[NSThread alloc]initWithTarget:self selector:@selector(buy) object:@""];
self.thread2=[[NSThread alloc]initWithTarget:self selector:@selector(buy) object:@""];
self.thread3=[[NSThread alloc]initWithTarget:self selector:@selector(buy) object:@""];
[_thread1 start];
_thread1.name=@"卖家01";
[_thread2 start];
_thread2.name=@"卖家02";
[_thread3 start];
_thread3.name=@"卖家03";
}
-(void)buy
{
while (1) {
@synchronized(self)//只能用一把锁
//多条线程同时抢夺同一个资源
//线程同步
{
NSInteger num=count;
if (num>0) {
count=num-1;
NSLog(@"%@卖了一张票,还剩下%ld张",[NSThread currentThread].name,(long)count);
}else{
NSLog(@"卖完了");
return;
}
}
}
}
标签:
原文地址:http://www.cnblogs.com/xiezefeng/p/5428038.html