swift 多线程
2018-08-07 本文已影响371人
倾倒的吞天壶
- 方式
- Thread(最轻,灵活度高)
- Cocoa Operation (队列+操作对象)
- Grand Central Dispatch(调度队列+操作对象)
- Thread
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//方式1:使用类方法
Thread.detachNewThreadSelector(#selector(ViewController.downloadImage),
toTarget: self, with: nil)
//方式2:实例方法-便利构造器
let myThread = Thread(target: self,
selector: #selector(ViewController.downloadImage),
object: nil)
myThread.start()
}
//定义一个下载图片的方法,线程调用
func downloadImage(){
let imageUrl = "http://hangge.com/blog/images/logo.png"
let data = try! Data(contentsOf: URL(string: imageUrl)!)
print(data.count)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
- Cocoa Operation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let operation = BlockOperation(block: { [weak self] in
self?.downloadImage()
return
})
//创建一个NSOperationQueue实例并添加operation
let queue = OperationQueue()
queue.addOperation(operation)
}
//定义一个下载图片的方法,线程调用
func downloadImage(){
let imageUrl = "http://hangge.com/blog/images/logo.png"
let data = try! Data(contentsOf: URL(string: imageUrl)!)
print(data.count)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//创建线程对象
let downloadImageOperation = DownloadImageOperation()
//创建一个OperationQueue实例并添加operation
let queue = OperationQueue()
queue.addOperation(downloadImageOperation)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
class DownloadImageOperation: Operation {
override func main(){
let imageUrl = "http://hangge.com/blog/images/logo.png"
let data = try! Data(contentsOf: URL(string: imageUrl)!)
print(data.count)
}
}
- DCG
//创建串行队列
let serial = DispatchQueue(label: "serialQueue1")
//创建并行队列
let concurrent = DispatchQueue(label: "concurrentQueue1", attributes: .concurrent)
//获取全局队列
let globalQueue = DispatchQueue.global(qos: .default)
//获取主线程队列
let mainQueue = DispatchQueue.main
//async异步追加Block块(async函数不做任何等待)
DispatchQueue.global(qos: .default).async {
//处理耗时操作的代码块...
print("do work")
//操作完成,调用主线程来刷新界面
DispatchQueue.main.async {
print("main refresh")
}
}
//添加同步代码块到global队列
//不会造成死锁,但会一直等待代码块执行完毕
DispatchQueue.global(qos: .default).sync {
print("sync1")
}
print("end1")
//添加同步代码块到main队列
//会引起死锁
//因为在主线程里面添加一个任务,因为是同步,所以要等添加的任务执行完毕后才能继续走下去。但是新添加的任务排在
//队列的末尾,要执行完成必须等前面的任务执行完成,由此又回到了第一步,程序卡死
DispatchQueue.main.sync {
print("sync2")
}
//创建并行队列
let conQueue = DispatchQueue(label: "concurrentQueue1", attributes: .concurrent)
//暂停一个队列
conQueue.suspend()
//继续队列
conQueue.resume()
//延时2秒执行
DispatchQueue.global(qos: .default).asyncAfter(deadline: DispatchTime.now() + 2.0) {
print("after!")
}
参考文章:
Swift - 多线程实现方式(1) - Thread
Swift - 多线程实现方式(2) - Operation和OperationQueue
Swift - 多线程实现方式(3) - Grand Central Dispatch(GCD)