#import"ViewController.h"
@interfaceViewController()
/**售票員A */
@property(nonatomic,strong)NSThread*threadA;
/**售票員B */
@property(nonatomic,strong)NSThread*threadB;
/**售票員C */
@property(nonatomic,strong)NSThread*threadC;
@property(nonatomic,assign)NSIntegertotalCount;
@end
@implementationViewController
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event
{
//設(shè)置中票數(shù)
self.totalCount=100;
self.threadA= [[NSThreadalloc]initWithTarget:selfselector:@selector(saleTicket)object:nil];
self.threadB= [[NSThreadalloc]initWithTarget:selfselector:@selector(saleTicket)object:nil];
self.threadC= [[NSThreadalloc]initWithTarget:selfselector:@selector(saleTicket)object:nil];
self.threadA.name=@"售票員A";
self.threadB.name=@"售票員B";
self.threadC.name=@"售票員C";
//啟動線程
@synchronized(self) {
[self.threadAstart];
[self.threadBstart];
[self.threadCstart];
}
-(void)saleTicket
{
while(1) {
//鎖:必須是全局唯一的
//1.注意枷鎖的位置
//2.注意枷鎖的前提條件,多線程共享同一塊資源
//3.注意加鎖是需要代價的,需要耗費性能的
//4.加鎖的結(jié)果:線程同步
@synchronized(self) {
//線程1
//線程2
//線程3
NSIntegercount =self.totalCount;
if(count >0) {
for(NSIntegeri =0; i<1000000; i++) {
}
self.totalCount= count -1;
//賣出去一張票
NSLog(@"%@賣出去了一張票,還剩下%zd張票", [NSThreadcurrentThread].name,self.totalCount);
}else
{
NSLog(@"賣完了");
break;
}