本篇內(nèi)容主要講解“如何使用線程Thread與Operation”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“如何使用線程Thread與Operation”吧!
專(zhuān)注于為中小企業(yè)提供網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)萬(wàn)全免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動(dòng)了1000+企業(yè)的穩(wěn)健成長(zhǎng),幫助中小企業(yè)通過(guò)網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
//Thread 原始方式 //Thread.detachNewThread 快捷方式創(chuàng)建Thread for i in 0...10 { Thread.detachNewThread{ print(i) } } /* 0 7 3 4 5 2 1 6 8 9 10 */
//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(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 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
到此,相信大家對(duì)“如何使用線程Thread與Operation”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢(xún),關(guān)注我們,繼續(xù)學(xué)習(xí)!