学计算机的那个

不是我觉到、悟到,你给不了我,给了也拿不住;只有我觉到、悟到,才有可能做到,能做到的才是我的.

0%

多线程面试题

面试题 1

假设我有一个类

1
2
3
4
5
6
7
8
9
@interface OrderPint : NSObject

- (id)init;
- (void)first;//打印"first"
- (void)second;//打印"second"
- (void)third;//打印"third"
- (void)run:(NSString *)order;

@end

三个不同的线程ABC将会共用一个 OrderPint 实例
线程A 会调用 first 方法
线程B 会调用 second 方法
线程C 会调用 third 方法

请完善OrderPint,让 first second third 按照指定的顺序被打印

例如
输入 @”123” 打印

1
2
3
first
second
third

输入 @”321” 打印

1
2
3
third
second
first

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];
}


//打印"first"
- (void)first{
NSLog(@"%@:first",[NSThread currentThread]);
}
//打印"second"
- (void)second{
NSLog(@"%@:second",[NSThread currentThread]);
}

//打印"third"
- (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