1,Swift继续使用Object-C原有的一套线程,包括三种多线程编程技术:

(1)NSThread
(2)Cocoa NSOperation(NSOperation和NSOperationQueue)
(3)Grand Central Dispath(GCD)
2,本文着重介绍NSThread
NSTread在三种多线程技术中是最轻量级的,但需要自己管理线程的生命周期和线程同步。线程同步对数据的加锁会有一定的系统开销。
3,NSThread的两种创建方式
(1)直接创建线程并且自动运行线程
(2)先创建一个线程对象,然后手动运行线程,在运行线程操作之前可以设置线程的优先级等线程信息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import UIKit
 
class ViewController: UIViewController {
 
    override func viewDidLoad() {
        super.viewDidLoad()
         
        //方式1:使用类方法
        NSThread.detachNewThreadSelector("downloadImage", toTarget: self, withObject: nil)
         
        //方式2:实例方法-便利构造器
        var myThread:NSThread = NSThread(target: self, selector: "downloadImage", object: nil)
        myThread.start()
    }
     
    //定义一个下载图片的方法,线程调用
    func downloadImage(){
        var imageUrl = "http://hangge.com/blog/images/logo.png"
        var data = NSData(contentsOfURL: NSURL(string: imageUrl)!, options: nil, error: nil)
        println(data?.length)
    }
     
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

4,线程同步

线程同步方法通过锁来实现,每个线程都只用一个锁,这个锁与一个特定的线程关联。下面演示两个线程之间的同步。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import UIKit
 
class ViewController: UIViewController {
     
    //定义两个线程
    var thread1:NSThread?
    var thread2:NSThread?
     
    //定义两个线程条件,用于锁住线程
    let condition1 = NSCondition()
    let condition2 = NSCondition()
 
    override func viewDidLoad() {
        super.viewDidLoad()
         
        thread2 = NSThread(target: self, selector: "method2:", object: nil)
        thread1 = NSThread(target: self, selector: "method1:", object: nil)
        thread1?.start()
    }
     
    //定义两方法,用于两个线程调用
    func method1(sender:AnyObject){
        for var i=0; i<10; i++ {
            print("NSThread 1 running \(i)")
            sleep(1)
             
            if i == 2 {
                thread2?.start() //启动线程2
                 
                //本线程(thread1)锁定
                condition1.lock()
                condition1.wait()
                condition1.unlock()
            }
        }
             
        print("NSThread 1 over")
         
        //线程2激活
        condition2.signal()
    }
     
    //方法2
    func method2(sender:AnyObject){
        for var i=0; i<10; i++ {
            print("NSThread 2 running \(i)")
            sleep(1)
             
            if i == 2 {
                //线程1激活
                condition1.signal()
                 
                //本线程(thread2)锁定
                condition2.lock()
                condition2.wait()
                condition2.unlock()
            }
        }
         
         print("NSThread 2 over")
    }
     
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

输出结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
NSThread 1 running 0
NSThread 1 running 1
NSThread 1 running 2
NSThread 2 running 0
NSThread 2 running 1
NSThread 2 running 2
NSThread 1 running 3
NSThread 1 running 4
NSThread 1 running 5
NSThread 1 running 6
NSThread 1 running 7
NSThread 1 running 8
NSThread 1 running 9
NSThread 1 over
NSThread 2 running 3
NSThread 2 running 4
NSThread 2 running 5
NSThread 2 running 6
NSThread 2 running 7
NSThread 2 running 8
NSThread 2 running 9
NSThread 2 over

Swift - 多线程实现方式(1) - NSThread的更多相关文章

  1. Swift - 多线程实现方式(2) - NSOperation和NSOperationQueue

    1,Swift继续使用Object-C原有的一套线程,包括三种多线程编程技术: (1)NSThread (2)Cocoa NSOperation(NSOperation和NSOperationQueu ...

  2. Swift - 多线程实现方式(3) - Grand Central Dispatch(GCD)

    1,Swift继续使用Object-C原有的一套线程,包括三种多线程编程技术: (1)NSThread (2)Cocoa NSOperation(NSOperation和NSOperationQueu ...

  3. iOS中的几种锁的总结,三种开启多线程的方式(GCD、NSOperation、NSThread)

    学习内容 欢迎关注我的iOS学习总结--每天学一点iOS:https://github.com/practiceqian/one-day-one-iOS-summary OC中的几种锁 为什么要引入锁 ...

  4. iOS开发Swift篇(02) NSThread线程相关简单说明

    iOS开发Swift篇(02) NSThread线程相关简单说明 一 说明 1)关于多线程部分的理论知识和OC实现,在之前的博文中已经写明,所以这里不再说明. 2)该文仅仅简单讲解NSThread在s ...

  5. 多线程(一)NSThread

    iOS中多线程的实现方案: 技术 语言 线程生命周期 使用频率 pthread C 程序员自行管理 几乎不用 NSthread OC 程序员自行管理 偶尔使用 GCD C 自动管理 经常使用 NSOp ...

  6. iOS多线程编程技术之NSThread、Cocoa NSOperation、GCD

    原文出处: 容芳志的博客 简介iOS有三种多线程编程的技术,分别是:(一)NSThread(二)Cocoa NSOperation(三)GCD(全称:Grand Central Dispatch) 这 ...

  7. java中创建多线程的方式

    在java中比较常用的有三种创建多线程的方式. 方式一:继承Thread类,要重写run方法. 在MyThread类 public class MyThread extends Thread { @O ...

  8. 实现多线程的方式之实现Callable接口

    package com.hls.juc; import java.util.concurrent.Callable;import java.util.concurrent.ExecutionExcep ...

  9. Java基础加强之并发(二)常用的多线程实现方式

    概述 常用的多线程实现方式有2种: 1. 继承Thread类 2. 实现Runnable接口 之所以说是常用的,是因为通过还可以通过JUC(java.util.concurrent)包中的线程池来实现 ...

随机推荐

  1. iOS UILabel 使用姿势大全(标红关键字)

    一.初始化 ? 1 2 3 UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 40, 120, 44)];       ...

  2. pycharm+QT4的helloworld

    # -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 exc ...

  3. HDU 3974 Assign the task 简单搜索

    根据Rex 的思路才知道可以这么写. 题目意思还是很好理解的,就是找到当前雇员最近的任务. 做法是,可以开辟一个 tim 变量,每次有雇员得到昕任务时候 ++tim 然后取寻找最近的任务的时候写一个搜 ...

  4. iOS: 在键盘之上显示一个 View

    如 AlertView,当 show 一个 Alert 时,它会覆盖在 Keyboard 上面,不影响显示的效果.那么我们自己创建的 View 如何像 Alert 那样不被键盘盖住呢?很简单,拿到 A ...

  5. Android 代码设置密码输入框内容的显示/隐藏

    //内容可见 mEtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); //内容不可见 m ...

  6. MFC的消息映射机制揭秘

    MFC的设计者们在设计MFC时,紧紧把握一个目标,那就是尽可能使得MFC的代码要小,速度尽可能快.为了这个目标,他们使用了许多技巧,其中很多技巧体现在宏的运用上,实现MFC的消息映射的机制就是其中之一 ...

  7. 使用webview来查看网站

    1.权限 <uses-permission android:name="android.permission.INTERNET"/> 2.视图 <Relative ...

  8. SQL -主键&外键

    在创建表的时候,添加主键 CREATE TABLE table_name (column_1 char(10) PRIMARY KEY, column_2 char(10) ) 如果已经创建了表,如何 ...

  9. 01-Foundation简介、NSObject、copy、NSString

    目录: 一.Foundation常用类 二.Foundation简介 三.NSObject 四.NSString 回到顶部 一.Foundation常用类 1 NSObject.NSString.NS ...

  10. Android 如何引用com.android.internal.R目录下的资源

    Android 如何引用com.android.internal.R目录下的资源 项目需求 有一个资源跟系统上的一个资源相同,想要引用它:frameworks/base/core/res/res/dr ...