iOS 面试题 3个线程顺序打印

题目1: 3个线程顺序打印 0-100

采用 NSCondition

- (void)print0_100 {
    
    __block int i = 0;
    dispatch_queue_t queueA = dispatch_queue_create("queue a", DISPATCH_QUEUE_CONCURRENT);
    dispatch_queue_t queueB = dispatch_queue_create("queue b", DISPATCH_QUEUE_CONCURRENT);
    dispatch_queue_t queueC = dispatch_queue_create("queue c", DISPATCH_QUEUE_CONCURRENT);

    NSCondition *condition = [[NSCondition alloc] init];
    
    dispatch_async(queueA, ^{
        while (1) {
            [condition lock];
            while (i%3 != 0) {
                [condition wait];
            }
            if (i > 100) {
                [condition unlock];
                return;
            }
            NSLog(@"A ==== i = %d",i);
            i++;
            [condition broadcast];
            [condition unlock];
        }
    });
    
    dispatch_async(queueB, ^{
        while (1) {
            [condition lock];
            while (i%3 != 1) {
                [condition wait];
            }
            if (i > 100) {
                [condition unlock];
                return;
            }
            NSLog(@"B ==== i = %d",i);
            i++;
            [condition broadcast];
            [condition unlock];
        }
    });

    dispatch_async(queueC, ^{
        while (1) {
            [condition lock];
            while (i%3 != 2) {
                [condition wait];
            }
            if (i > 100) {
                [condition unlock];
                return;
            }
            NSLog(@"C ==== i = %d",i);
            i++;
            [condition broadcast];
            [condition unlock];
        }
    });

}

输出


image.png

题目2: 启动三个线程A,B,C,打印10次 按照ABC的顺序输出

采用 NSConditionLock

- (void)printA_B_C {
    
    dispatch_queue_t queueA = dispatch_queue_create("queue a", DISPATCH_QUEUE_CONCURRENT);
    dispatch_queue_t queueB = dispatch_queue_create("queue b", DISPATCH_QUEUE_CONCURRENT);
    dispatch_queue_t queueC = dispatch_queue_create("queue c", DISPATCH_QUEUE_CONCURRENT);

    NSConditionLock *conditionLock = [[NSConditionLock alloc] initWithCondition:0];
    dispatch_async(queueA, ^{
        for (int i = 0; i< 10; i++) {
            [conditionLock lockWhenCondition:0];
            NSLog(@"A = %d", i);
            [conditionLock unlockWithCondition:1];
        }
    });
    
    dispatch_async(queueB, ^{
        for (int i = 0; i< 10; i++) {
            [conditionLock lockWhenCondition:1];
            NSLog(@"B = %d", i);
            [conditionLock unlockWithCondition:2];
        }
    });

    dispatch_async(queueC, ^{
        for (int i = 0; i< 10; i++) {
            [conditionLock lockWhenCondition:2];
            NSLog(@"C = %d", i);
            [conditionLock unlockWithCondition:0];
        }
    });
}

输出:

image.png

也可以使用3个 NSLock 或者 dispatch_semaphore
参考iOS多线程面试题-启动三个线程A,B,C,打印10次 按照ABC的顺序输出(异步转同步

你可能感兴趣的:(iOS 面试题 3个线程顺序打印)