zoukankan      html  css  js  c++  java
  • 多线程之NSThread

    关于多线程会有一系列如下:
    多线程之概念解析 

    多线程之pthread, NSThread, NSOperation, GCD

    多线程之NSThread

    多线程之NSOperation

    多线程之GCD

    一,创建线程

    • 动态创建
    /**
     动态创建
     */
    - (void)dynamicCreateThread {
        // 动态创建
        // 动态创建的线程,必须调用 start ,线程才会跑起来
        NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(dynamicRun:) object:@1];
        thread.threadPriority = 1;//0-1,1的优先级最高
        thread.name = @"dynamic thread";
        [thread start];
        
        // iOS10 以后新添加的方法
        NSThread *newThread = [[NSThread alloc] initWithBlock:^{
            NSLog(@"block operation");
        }];
        [newThread start];
    }
    
    
    
    - (void)dynamicRun:(NSNumber *)index {
        NSLog(@"thread = %@", [NSThread currentThread]);
        NSLog(@"index = %@", index);
        NSLog(@"dynamic run");
        NSLog(@"name = %@", [NSThread currentThread].name);
    }
    • 静态创建

    /** 静态创建 */ - (void)staticCreateThread { // 静态创建 [NSThread detachNewThreadSelector:@selector(staticRun) toTarget:self withObject:nil]; // ios 10以后才出现 [NSThread detachNewThreadWithBlock:^{ [self staticRun]; }]; }

    • 隐式创建
    /**
     隐式创建
     */
    - (void)backgroundCreateThread {
        [self performSelectorInBackground:@selector(backgroundRun) withObject:nil];
    }
    • 线程通信
    - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
    
    - (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait;

    二.属性

     @property (class, readonly, strong) NSThread *currentThread;//获取当前线程

    @property (nullable, copy) NSString *name // 线程名
    @property double threadPriority //优先级,0-1, 1的优先级最高
    @property NSUInteger stackSize // 线程所占用内存
    @property (readonly) BOOL isMainThread // 是否为主线程

    状态相关

    @property (readonly, getter=isExecuting) BOOL executing 
    @property (readonly, getter=isFinished) BOOL finished 
    @property (readonly, getter=isCancelled) BOOL cancelled


    三.API

    + (BOOL)isMultiThreaded;// 判断当前线程是否是多线程
    
    //线程操作
    
    - (void)start;
    
    - (void)cancel;
    
    + (void)exit;
    
    - (void)main;// thread body method
    
    // 线程阻塞
    
    + (void)sleepUntilDate:(NSDate *)date;
    
    + (void)sleepForTimeInterval:(NSTimeInterval)ti;
    
     
    // 获取线程
    @property (class, readonly, strong) NSThread *currentThread;//获取当前线程
    @property (class, readonly, strong) NSThread *mainThread;//获取主线程

    四.自定义NSThread

      注意:  通过静态方法创建的 thread不会执行 main 方法

      











  • 相关阅读:
    01Angular开发环境配置
    不再显示广告案例(php操作cookie)
    php操作 cookie
    JPush Android 推送如何区分开发、生产环境
    10 分钟实现一个自己的服务器监控器
    iOS 轻松使用 App 数据统计
    认识本质:黑天鹅、关键时刻与张小龙的产品观
    C# 服务端推送,十步十分钟,从注册到推送成功
    聊天界面-自适应文字
    极光推送的角标问题——让人又爱又恨的小红点
  • 原文地址:https://www.cnblogs.com/shidaying/p/6931333.html
Copyright © 2011-2022 走看看