• 线程篇-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
    
  • 相关阅读:
    移动端rem切图
    在Vue中如何使用axios跨域访问数据
    如何使地图和柱状图联动
    dedecms 5.7 采集目标文章的发布时间 采集后变成当前本地时间
    PHP的内存限制 Allowed memory size of 134217728 bytes exhausted (tried to allocate 1099 bytes) in
    Web前端性能优化——如何提高页面加载速度
    jquery中链式调用原理
    jdk1.6以后 对synchronized锁做了哪些优化
    Synchronized的锁优化
    分布式缓存
  • 原文地址:https://www.cnblogs.com/objectc/p/4884063.html
Copyright © 2020-2023  润新知