线程篇-01-NSThread


一.概述

1.使用NSThread创建线程的三种方式和区别.

二.核心

2.1 NSThread创建线程的三种方式和区别.

主要有NSThread对象的创建线程的类方法detachNewThreadSelector:方法, alloc(initWithTarget:selector:object:)方法, performSelectorInBackground:方法.

区别:

1.是前后两种创建线程的方法, 无法拿到线程, 所以无法给线程设置一些额外信息, 如线程名字等.而且也无法控制线程除创建之外的状态.而中间这种方法能拿到线程, 给线程设置名字, 还能控制让线程休眠等.

2.前后两者不仅仅会创建线程还会自动启动线程,而中间使用alloc, initWithTarget:selector:object这种则要手动启动.拿到对应的线程对象, 调用start的方法.

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

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

- (void)createThread1 {
    
    // 使用NSThread第一种创建线程的方式
    // 在这个线程上执行当前对象的run方法, 传递进来的参数是swp
    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"swp"];
    
}

- (void)createThread2 {
    // 使用NSThread第一种创建线程的方式
    // 在这个线程上执行当前对象的run方法, 传递进来的参数是swp2
    [self performSelectorInBackground:@selector(run:) withObject:@"swp2"];
    
}

- (void)createThread3 {
    
    NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"swp3"];
    // 需要手动启动线程, 而前面两种不用手动启动, 会在创建完后自动启动线程.
    // 让CPU立即切换到该线程执行, 其任务就是运行run方法.
    [thread start];
}

- (void)run:(NSString *)param {
    
    for (int i = 0; i < 100; i++) {
        
        NSLog(@"run----%@---%@", [NSThread currentThread], param);
    
    }
    
}


@end


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM