Swift实现多线程的三种方式
实现多线程的方式有三种:
Thread,
Cocoa Operation(Operation和OperationQueue),
Grand Central Dispath(GCD)
Thread实现
快捷方式实现
import UIKit
import PlaygroundSupport
//不希望主线程代码实现完成之后就退出了
PlaygroundPage.current.needsIndefiniteExecution = true;
//快捷方式实现
for i in 0..<10 {
Thread.detachNewThread {
print(i)
}
}
初始化器
import UIKit
import PlaygroundSupport
//不希望主线程代码实现完成之后就退出了
PlaygroundPage.current.needsIndefiniteExecution = true;
//初始化器
class ObjectThread {
func threadTest() {
let thread = Thread(target: self, selector: #selector(threadExecute), object: nil)
thread.start()
}
@objc func threadExecute() {
print("threadExecuting1")
}
}
let obj = ObjectThread();
obj.threadTest()
Cocoa Operation(Operation和OperationQueue)实现
BlockOperation实现
import UIKit
import