美文网首页
IOS多线程-pthread & NSThread

IOS多线程-pthread & NSThread

作者: mr_young_ | 来源:发表于2017-03-06 11:20 被阅读13次

一、pthread的使用(几乎不用)

#import "ViewController.h"
// 1.引入pthread头文件: #import <pthread.h>
#import <pthread.h>

@interface ViewController ()

@end

@implementation ViewController

void *run(void *data) {
    for (int i = 0; i<10000; i++) {
        // 调用NSThread的类方法currentThread返回的是
        // 当前代码所在线程的相关信息(线程地址,线程数量,当前线程的名字)
        NSLog(@"touchesBegan ---- %d --- %@", i, [NSThread currentThread]);
    }
    return 0;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 2.创建线程
    pthread_t myRestict;
    // 3.启动线程,调用run方法,注意⚠️run方法的返回值必须为空!
    pthread_create(&myRestict, NULL, run, NULL);
}

@end

二、NSThread的使用(偶尔使用)

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)download:(NSString *)url {
    NSLog(@"download something --- %@ --- %@", url, [NSThread currentThread]);
}

/**
 创建线程的方式1
 */
- (void)createThread1 {
    // 1.创建线程
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"http://a.jpg"];
    
    // 2.启动线程(调用self的download方法)
    [thread start];
    
    // 判断thread这个线程是否是主线程
    // [thread isMainThread];
    
    // 判断当前方法是否为主线程
    // [NSThread isMainThread];
    
    // 设置线程的名字
    // [thread setName:@"download_thread"];
    // thread.name = @"downloadThread";
}

/**
 创建线程的方式2: 创建线程后自动启动
 */
- (void)createThread2 {
    [NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http://b.png"];
}

/**
 创建线程的方式3: 隐式创建线程后自动启动
 */
- (void)createThread3 {
    [self performSelectorInBackground:@selector(download:) withObject:@"http://c.gif"];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self createThread1];
    // [self createThread2];
    // [self createThread3];
}

@end

相关文章

  • OC_NSThread

    原文链接:iOS多线程--彻底学会多线程之『pthread、NSThread』 **NSThread **是苹果官...

  • 多线程(2)——NSThread

    iOS中实现多线程的四种方案 pthread NSThread GCD NSOpreation Pthread:这...

  • iOS多线程.md

    2018-05-22 iOS多线程-概念iOS多线程:『pthread、NSThread』详尽总结 多线程-概念图...

  • iOS多线程

    iOS中常用的多线程:pthread:C语言 NSThread:OC GCD:C NSOpreration:...

  • IOS多线程-pthread & NSThread

    一、pthread的使用(几乎不用) 二、NSThread的使用(偶尔使用)

  • 多线程、Runloop、Runtime

    多线程 iOS多线程技术有哪几种方式pthread、NSThread、GCD、NSOperation 1. NSO...

  • iOS多线程

    iOS中常见的多线程方案 pthread NSThread GCD NSOperation GCD GCD执行任务...

  • NSOperation学习

    iOS的多线程技术主要有:pthread、NSThread、NSOperation、GCD。怎么选呢?pthrea...

  • iOS底层原理(四):多线程

    一、GCD iOS中常见的多线程方案有:pthread、NSThread、GCD、NSOperation,我们用的...

  • 底层原理:多线程

    iOS中常见多线程方案 NSThread 、 GCD 和 NSOperation 底层都是依赖于 pthread ...

网友评论

      本文标题:IOS多线程-pthread & NSThread

      本文链接:https://www.haomeiwen.com/subject/silegttx.html