多线程之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 方法

  











 

 

posted @ 2017-06-01 23:37  shidaying  阅读(235)  评论(0编辑  收藏  举报