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 方法

      











  • 相关阅读:
    记坑
    常用模板
    ACM-东北赛划水记
    jzoj 4178游戏
    JZOI 4163
    jzoj 4146踩气球
    jzoj 5589. 缩点
    jzoj 5588 %%%
    jzoj 5571 ffs
    BJOI 2017 Kakuro
  • 原文地址:https://www.cnblogs.com/shidaying/p/6931333.html
Copyright © 2011-2022 走看看