程序员我是程序员;您好程先生;叫我序员就好了iOS Developer

多线程基础01 概念和NSThread

2016-05-12  本文已影响69人  CoderMacro

阅读原文-关注我的博客


在软件开发中必不可少的会接触到一个词语--多线程;
那么什么是多线呢,本文主要是对多线程的基础知识做简单讲解。


1 基本概念

1.1 进程的概念

1.2 线程的概念

1.3 多线程的概念

多线程原理
多线程优缺点
多线程在iOS开发中的应用

2 iOS中多线程的实现方案

3 pthread的例子

    - (void)viewDidLoad {
        [super viewDidLoad];
        
        // 创建一个线程标识符
        pthread_t myrestrict;
        
        // 1param 线程标识符变量的地址, 2param 写NULL 3param 执行的的函数 4param NULL
        pthread_create(&myrestrict, NULL, run, NULL);
    }
    
    // 定义线程的函数
    void *run(void *data) {
        
        NSLog(@"%@", [NSThread currentThread]);
        
        return nil;
    }

4 NSThread的基本用法

创建方式1 创建后需启动

//创建线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download) object:nil];
        
// 启动线程
[thread start];

创建方式2 创建后自动启动

// 创建后直接启动  传一个字符串
[NSThread detachNewThreadSelector:@selector(download2:) toTarget:self withObject:@"param"];

创建方式3 隐式启动

// 开启子线程
[self performSelectorInBackground:@selector(download) withObject:nil];
        
// 开启主线程
[self performSelector:@selector(download) withObject:nil];

// 开启传入的线程
[self performSelector:@selector(download) onThread:[NSThread currentThread] withObject:nil waitUntilDone:NO];

其它常用方法

// 获取当前线程
NSThread *current = [NSThread currentThread];
// 获取主线程
NSThread *main = [NSThread mainThread];
// 判断是否主线程-类方法
BOOL isMain = [NSThread isMainThread];
// 判断是否主线程-对象方法
BOOL isMain2 = [main isMainThread];
// 给线程起名字
current.name = @"下载线程";
// 线程睡眠状态5秒
[NSThread sleepForTimeInterval:5.0];
// 线程睡眠从现在开始3秒以后的时间
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:3]];
// 线程退出 线程进入死亡状态
[NSThread exit];

线程之间的通信

[self performSelectorOnMainThread:@selector(method) withObject:nil waitUntilDone:YES];
    
[self performSelector:@selector(method) onThread:[NSThread mainThread] withObject:nil waitUntilDone:YES];

5.线程安全

@synchronized(self) { 
    // 插入锁定代码 
  }
* >注意 : 一份代码只能用一个锁, 多个锁无效

6.多线程状态示意图

在了解完线程安全后咱们再看看完整的线程状态示意图
上一篇 下一篇

猜你喜欢

热点阅读