多线程交替输出字符串(1)

  • 看到一个题目,多个线程交替输出 AB0CD1EF2GH3...

  这个可以使用多种实现,主要考察线程之间的同步方式。

  线程之间的同步方式有多种,这里采用第一种

  

import Foundation
var run: Bool = true
/// 将字符转成UInt8
func charToInt(chr: Character) -> UInt8? {
    return chr.asciiValue
}
/// 将Uint8转成字符
func intToChr(asciiValue: UInt8) -> Character? {
    return Character(UnicodeScalar(asciiValue))
}
///
let group = DispatchGroup()
group.enter()
let condition1 = NSCondition()
let condition2 = NSCondition()
guard var start1: UInt8 = charToInt(chr: Character("A")) else {
    exit(-1)
}
let t1 = Thread(block: {
    while run {
        sleep(1)
        let first = (start1 - 65) % 26 + 65
        start1 = start1 + 1
        let second = (start1 - 65) % 26 + 65
        start1 = start1 + 1
        print("\(intToChr(asciiValue: first)!), \(intToChr(asciiValue: second)!)")
        condition2.signal()
        condition1.wait()
    }
    group.leave()
})
group.enter()
var start2 = 0
let t2 = Thread(block: {
    while run {
        sleep(1)
        condition2.wait()
        print("\(start2 % 10)")
        start2 = start2 + 1
        condition1.signal()
    }
    group.leave()
})

 

 

posted @ 2021-03-12 21:51  兜兜有糖的博客  阅读(185)  评论(0编辑  收藏  举报