上代碼
import UIKit
class ViewController: UIViewController {
var tickets = 100
var theardA:Thread?
var theardB:Thread?
override func viewDidLoad() {
super.viewDidLoad()
theardA = Thread.init(target: self, selector: #selector(sale), object: nil)
theardA?.name = "A窗口"
theardB = Thread.init(target: self, selector: #selector(sale), object: nil)
theardB?.name = "B窗口"
}
@objc func sale () {
for i in 1...100 {
buyTicket(username: "person\(i)")
}
}
//開始買票
@IBAction func begain(_ sender: UIButton) {
theardA?.start()
theardB?.start()
}
///objc_sync_enter(lockString)
///objc_sync_exit(lockString)
func buyTicket(username: String) {
Thread.sleep(forTimeInterval: 0.5)
///加上互斥鎖,保護(hù)資源 同一時刻只能被一個線程讀寫
objc_sync_enter(self)
self.tickets -= 1
let currentName = Thread.current.name! as String
print("\(username)在\(currentName)買了一張票靡狞,剩余票數(shù):\(self.tickets)")
objc_sync_exit(self)
}
}