iOS开发学习iOS Developer

iOS 线程安全小事例

2017-05-29  本文已影响38人  BEYOND黄

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

}

上一篇下一篇

猜你喜欢

热点阅读