swift基本文法-多線程

來源:互聯網
上載者:User

標籤:

實現多線程的方式以及優勢:

    1、NSThread

        輕量級最輕,但需要自己管理線程的生命週期和線程同步。線程同步對資料的加鎖會有一定的系統消耗。

    2、Cocoa NSOpertion(NSOpertion 和 NSOpertionQuene)

        Cocoa NSOpertion 不需要關心線程管理和資料同步的事情。相關的類有NSOpertion 和 NSOpertionQuene。啟動NSOpertion 是個抽象類別,使用它必須用他的子類,可以實現它或者它定義好的兩個子類: NSInvocationOpertion 和 NSBlockOperation。建立NSOpertion 子類的對象,把對象添加到NSOpertionQuene 隊列裡執行

    3、Grand Central Dispatch(GCD)

        GCD 是 apple開發的一個多核編程的解決辦法。再mac os x10.6 雪豹中首次推出,並隨後被引入到了ios4.0 中。GCD是一個替代 NSThread、NSOperationQueue、NSInvocationOperation等技術的一種高效強大的技術。其抽象程度最高,使用簡單,是apple 最推薦使用的。


-----好了,廢話終於敲完了-------

1、NSThread 例子

    1.1 通過整合NSThread

////  main.swift//  swift_lession1////  Created by shaoyongyang on 15/5/24.//  Copyright (c) 2015年 shaoyongyang. All rights reserved.//import Foundationclass bigDog:NSThread {        func hello() {        //NSThread.detachNewThreadSelector("otherThread", toTarget: self, withObject: nil)        var myThread:NSThread = NSThread(target: self, selector: "otherThread", object: nil)        myThread.start()        println(NSThread.currentThread())    }        func otherThread() {        println(NSThread.currentThread())        println("hello! i am other thread...")    }}var dog = bigDog()println(dog.hello())for var i=0;i<100000;i++ {    }
NSThread.detachNewThreadSelector("otherThread", toTarget: self, withObject: nil)//不需要start,直接執行函數

2、Cocoa NSOperation 例子

3、Grand Central Dispatch 例子


swift基本文法-多線程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.