面试题 1
假设我有一个类
1 2 3 4 5 6 7 8 9
| @interface OrderPint : NSObject
- (id)init; - (void)first; - (void)second; - (void)third; - (void)run:(NSString *)order;
@end
|
三个不同的线程ABC将会共用一个 OrderPint
实例
线程A 会调用 first
方法
线程B 会调用 second
方法
线程C 会调用 third
方法
请完善OrderPint
,让 first
second
third
按照指定的顺序被打印
例如
输入 @”123” 打印
输入 @”321” 打印
Demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| #import "OrderPint.h"
@interface OrderPint () @property (nonatomic) dispatch_semaphore_t semaphore; @end
@implementation OrderPint
-(id)init{ _semaphore = dispatch_semaphore_create(1); return [super init]; }
- (void)first{ NSLog(@"%@:first",[NSThread currentThread]); }
- (void)second{ NSLog(@"%@:second",[NSThread currentThread]); }
- (void)third{ NSLog(@"%@:third",[NSThread currentThread]); }
- (void)run:(NSString *)order{ if (order.length == 3){ dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_group_t group = dispatch_group_create(); dispatch_group_async(group, queue, ^{ [self transferToFunction:[order substringWithRange:NSMakeRange(0, 1)]]; [self signal]; }); [self wait]; dispatch_group_async(group, queue, ^{ [self transferToFunction:[order substringWithRange:NSMakeRange(1, 1)]]; [self signal]; }); [self wait]; dispatch_group_async(group, queue, ^{ [self transferToFunction:[order substringWithRange:NSMakeRange(2, 1)]]; [self signal]; }); } }
-(void)transferToFunction:(NSString*) str { if ([str isEqualToString: @"1"]){ [self first]; }else if ([str isEqualToString: @"2"]){ [self second]; }else if ([str isEqualToString: @"3"]){ [self third]; } }
- (void)wait { dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER); }
- (void)signal { dispatch_semaphore_signal(_semaphore); } @end
|