码迷,mamicode.com
首页 > 编程语言 > 详细

swift基本语法-多线程

时间:2015-05-27 01:14:02      阅读:322      评论:0      收藏:0      [点我收藏+]

标签:

实现多线程的方式以及优势:

    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 Foundation

class 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基本语法-多线程

标签:

原文地址:http://my.oschina.net/0x4ad/blog/420347

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!