iOS开发多线程篇---线程锁(线程安全)
@interface BTThreadViewController () { NSThread *OneThread;//师傅一 NSThread *TwoThread;//师傅二 NSThread *ThreeThread;//师傅三 int allCake;//蛋糕总数 } @end @implementation BTThreadViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; [self myThread]; } -(void)myThread { allCake = 10; //给每个线程起一个名字,方便下面区分 OneThread = [[NSThread alloc] initWithTarget:self selector:@selector(SendTheCake) object:nil]; OneThread.name = @"师傅一"; [OneThread start]; TwoThread = [[NSThread alloc] initWithTarget:self selector:@selector(SendTheCake) object:nil]; TwoThread.name = @"师傅二"; [TwoThread start]; ThreeThread = [[NSThread alloc] initWithTarget:self selector:@selector(SendTheCake) object:nil]; ThreeThread.name = @"师傅三"; [ThreeThread start]; } -(void)SendTheCake { while (1) { //线程锁的优点:能有效防止因多线程抢夺资源造成的数据安全问题,缺点:需要消耗大量的CPU资源,线程锁的使用前提:多条线程抢夺同一块资源,相关专业术语:线程同步,多条线程按顺序地执行任务。线程锁,就是使用了线程同步技术 @synchronized(self){ if (allCake > 0) { //线程休眠时间 [NSThread sleepForTimeInterval:0.002]; //蛋糕个数-1 allCake -= 1; //打印当前的线程和剩余蛋糕数量 NSThread *senderThread = [NSThread currentThread]; NSLog(@"--%@发了1个蛋糕,还剩下%d个蛋糕",senderThread,allCake); } else { //退出线程 [NSThread exit]; } } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。