使用NSCondition控制线程同步通信:NSCondition 可以让那些已经锁定的NSCondition对象却无法继续使用执行的线程释放NSCondition对象,NSCondition对象也可以唤醒其他处于等待状态的线程;
-wait :导致线程当前线程一直等待,开题报告,直到其他线程调用NSCondition的signal方法或broadcast方法唤醒该线程,waitUntilDtae:
-signal:唤醒等待的单个线程;选择是任意性的,
-broadcast:唤醒所有线程;
#import 'Acount.h' @implementation Acount -(instancetype)init { self=[super init ]; if (self) { _cond=[NSCondition new]; } return self; } -(instancetype)initWithCountNo:(NSString *)acountNo balance:(float)balance { self=[super init]; if (self) { _cond=[NSCondition new]; _acountNo=acountNo; _balance=balance; } return self; } -(void)draw:(float)drawNum { [_cond lock]; //flag=no没钱取钱阻塞; if (drawNum>_balance) { _flag=NO; } else { _flag=YES; } if (!_flag) { NSLog(@'等待存钱drawNum:%f,_balance:%f',drawNum,_balance); [_cond wait]; }else { NSLog(@'%@取钱:%g', [NSThread currentThread].name,drawNum); _balance-=drawNum; NSLog(@'账户余额:%g',_balance); [_cond broadcast]; } [_cond unlock]; } -(void)deposit:(float)depositNum { [_cond lock]; NSLog(@'%@存钱:%g', [NSThread currentThread].name,depositNum); _balance+=depositNum; NSLog(@'账户余额:%g',_balance); [_cond broadcast]; [_cond unlock]; } =============================================================================================================================== - (void)viewDidLoad { [super viewDidLoad]; _account=[[Acount alloc]initWithCountNo:@'123' balance:1000.0]; } - (IBAction)DepositAndDraw:(id)sender { [NSThread detachNewThreadSelector:@selector(drawMethod:) toTarget:self withObject:[NSNumber numberWithDouble:800.0]]; [NSThread detachNewThreadSelector:@selector(drawMethod:) toTarget:self withObject:[NSNumber numberWithDouble:800.0]]; [NSThread detachNewThreadSelector:@selector(drawMethod:) toTarget:self withObject:[NSNumber numberWithDouble:800.0]]; [NSThread detachNewThreadSelector:@selector(depositMethod:) toTarget:self withObject:[NSNumber numberWithDouble:800.0]]; } -(void)depositMethod:(NSNumber*)depositNum { [NSThread currentThread].name=@'A存钱'; for (int i=0; i<100; i++) { [_account deposit:[depositNum floatValue]]; } } -(void)drawMethod:(NSNumber*)drawNum { [NSThread currentThread].name=@'B取钱'; for (int i=0 ; i<100; i++) { [_account draw:[drawNum floatValue]]; } },开题报告