iOS 线程安全小事例

作者: BEYOND黄 | 来源:发表于2017-05-29 18:53 被阅读38次

#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

{

//设置中票数

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.加锁的结果:线程同步

@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;

}

相关文章

网友评论

    本文标题:iOS 线程安全小事例

    本文链接:https://www.haomeiwen.com/subject/puclfxtx.html