swift基础之线程Thread & Operation

原创
2021/04/16 16:54
阅读数 83

Thread

//Thread 原始方式

//Thread.detachNewThread 快捷方式创建Thread
for i in 0...10 {
    Thread.detachNewThread{
        print(i)
    }
}
/*
 0
 7
 3
 4
 5
 2
 1
 6
 8
 9
 10
 */

Thread.detachNewThreadSelector

//Thread.detachNewThreadSelector
class ObjectForThread {
    func threadTest() {
        let thread = Thread(target: self, selector: #selector(threadWorker), object: nil)
        thread.start()
        print("threadTest")
    }
    
    @objc func threadWorker() {
        print("threadWorker")
    }
}
let obj = ObjectForThread()
obj.threadTest()
/*
 threadTest
 threadWorker
 */

Cocoa Operation

//Cocoa Operation(Operation和OperationQueue)
class ObjectOperation {
    func test() {
        let operation = BlockOperation{ [weak self] in
            self?.threadWorker()
        }
        let queue = OperationQueue()
        queue.addOperation(operation)
    }
    
    @objc func threadWorker() {
        sleep(1)
        print("threadWorker")
    }
}

let objOperation = ObjectOperation()
objOperation.test()
print("after invoke test")
//after invoke test
//threadWorker

自定义Operation

//自定义Operation
class MyOperation: Operation {
    override func main() {
        sleep(1)
        print("MyOperation main")
    }
}

class CustomOperation {
    func test() {
        let operation = MyOperation()
        operation.completionBlock = { () -> Void in
            print("completionBlock")
        }
        let queue = OperationQueue()
        queue.addOperation(operation)
    }
}

let customOperation = CustomOperation()
customOperation.test()
print("after invoke customOperation test")
//after invoke customOperation test
//MyOperation main
//completionBlock
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部