zoukankan      html  css  js  c++  java
  • 线程篇-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
    
  • 相关阅读:
    160-三个用户同时登录,是怎么实现多线程的?
    159-如何解决缓存穿透?
    158-为什么会引发缓存穿透?
    存储emoji表情,修改字符集为utf8mb4
    java相差小时数
    pom.xml解释
    前端 跨域
    java 获取的是本地的IP地址
    是否超时
    发送验证码
  • 原文地址:https://www.cnblogs.com/objectc/p/4884063.html
Copyright © 2011-2022 走看看