最近在对比Objective-c学习Swift
创建线程执行一个方法就结束线程,这种可以用GCD或者queue实现,没必要浪费资源创建一个新线程。本文中说的创建线程是创建一个不会结束的线程
直接上干货,Objective-c中创建线程参考AFNetworking 2中的方法:
Jietu20170502-152309@2x.jpgSwift中创建不结束的线程同样需要显示的启动runloop
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
createThreadOne()
createThreadTwo()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func createThreadOne() {
let newThread = Thread.init(target: self, selector: #selector(threadOne), object: nil)
newThread.start()
}
func threadOne() {
print("thread one func")
Timer.scheduledTimer(withTimeInterval: 2, repeats: true, block: { (timer) in
print("thread one")
})
RunLoop.current.add(Port(), forMode: .commonModes)
RunLoop.current.run()
}
func createThreadTwo() {
Thread.detachNewThreadSelector(#selector(threadTwo), toTarget: self, with: nil)
}
func threadTwo() {
print("thread two func")
Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: {
(timer) in
print("thread two")
})
RunLoop.current.add(Port(), forMode: .commonModes)
RunLoop.current.run()
}
网友评论