NSCondition模擬買票的過程的簡單實現

end5 9年前發布 | 719 次閱讀 Objective-C IOS

@interface ViewController ()

@property (nonatomic, strong) NSMutableArray * array;

@property (nonatomic, strong) NSCondition * condition;

@property (nonatomic, strong) NSTimer * timer;

@end

@implementation ViewController

//初始化

  • (NSMutableArray *)array

{

if (!_array) {

    _array = [NSMutableArray array];

}

return _array;

}

  • (NSCondition *)condition

{

if (!_condition) {

    _condition = [[NSCondition alloc] init];

}

return  _condition;

}

//加載

  • (void)viewDidLoad {

    [super viewDidLoad];

//購買

for (int i = 0; i<3; i++)

{

    [self performSelectorInBackground:@selector(_consumer) withObject:nil];

}



//生產

self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(_productor) userInfo:nil repeats:YES];



}

  • (void)_productor

{

[self.condition lock];



if (self.array.count != 0)

{

    NSLog(@"結束");

    [self.timer invalidate];

    self.timer = nil;

}

else

{

    [self.array addObject:@"aaa"];

    NSLog(@"生產完成!");

    [self.condition signal];

}



[self.condition unlock];





}

  • (void)_consumer

{

[self.condition lock];



if (self.array.count <= 0)

{

    NSLog(@"正在等待!");

    [self.condition wait];

}



[self.array removeLastObject];

NSLog(@"購買成功!");



[self.condition unlock];

}

@end </pre>

 本文由用戶 end5 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!