JHHK

欢迎来到我的个人网站
行者常至 为者常成

NSThread

目录

基本使用

//获取当前线程
NSThread * currentThread = [NSThread currentThread];
NSLog(@"currentThread = %@",currentThread);

//获取主线程
NSThread * mainThread = [NSThread mainThread];
NSLog(@"mainThread=%@",mainThread);

//查看是否是主线程
BOOL isMain = [NSThread isMainThread];
NSLog(@"isMain=%d",isMain);

创建线程

__weak typeof(self) weakSelf = self;
NSThread * thread = [[NSThread alloc] initWithBlock:^{
    [weakSelf.task sailTicket:10];
}];

[thread start];

线程保活

封装方式一:
LCPermenantThread.h

#import <Foundation/Foundation.h>

typedef void (^LCPermenantThreadTask)(void);

@interface LCPermenantThread : NSObject

/**
 开启线程
 */
//- (void)run;

/**
 在当前子线程执行一个任务
 */
- (void)executeTask:(LCPermenantThreadTask)task;

/**
 结束线程
 */
- (void)stop;

@end

LCPermenantThread.m

#import "LCPermenantThread.h"

/** LCThread **/
@interface LCThread : NSThread
@end
@implementation LCThread
- (void)dealloc
{
    NSLog(@"%s", __func__);
}
@end

/** LCPermenantThread **/
@interface LCPermenantThread()
@property (strong, nonatomic) LCThread *innerThread;
@property (assign, nonatomic, getter=isStopped) BOOL stopped;
@end

@implementation LCPermenantThread
#pragma mark - public methods
- (instancetype)init
{
    if (self = [super init]) {
        self.stopped = NO;
        
        __weak typeof(self) weakSelf = self;
        
        self.innerThread = [[LCThread alloc] initWithBlock:^{
            [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
            
            while (weakSelf && !weakSelf.isStopped) {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            }
        }];
        
        [self.innerThread start];
    }
    return self;
}

//- (void)run
//{
//    if (!self.innerThread) return;
//
//    [self.innerThread start];
//}

- (void)executeTask:(LCPermenantThreadTask)task
{
    if (!self.innerThread || !task) return;
    
    [self performSelector:@selector(__executeTask:) onThread:self.innerThread withObject:task waitUntilDone:NO];
}

- (void)stop
{
    if (!self.innerThread) return;
    
    [self performSelector:@selector(__stop) onThread:self.innerThread withObject:nil waitUntilDone:YES];
}

- (void)dealloc
{
    NSLog(@"%s", __func__);
    
    [self stop];
}

#pragma mark - private methods
- (void)__stop
{
    self.stopped = YES;
    CFRunLoopStop(CFRunLoopGetCurrent());
    self.innerThread = nil;
}

- (void)__executeTask:(LCPermenantThreadTask)task
{
    task();
}

@end

使用

//创建一个线程
self.thread = [[LCPermenantThread alloc] init];

//执行task
[self.thread executeTask:^{
    NSLog(@"执行任务 - %@", [NSThread currentThread]);
}];

[self.thread executeTask:^{
    NSLog(@"执行任务2 - %@", [NSThread currentThread]);
}];

//停止当前线程的runloop 线程回收
[self.thread stop];

创建方式二:
init 方法可以用下面的方式实现

- (instancetype)init
{
    if (self = [super init]) {
        self.innerThread = [[LCThread alloc] initWithBlock:^{
            NSLog(@"begin----");
            
            // 创建上下文(要初始化一下结构体)
            CFRunLoopSourceContext context = {0};
            
            // 创建source
            CFRunLoopSourceRef source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context);
            
            // 往Runloop中添加source
            CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
            
            // 销毁source
            CFRelease(source);
            
            // 启动
            CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e10, false);
            
//            while (weakSelf && !weakSelf.isStopped) {
//                // 第3个参数:returnAfterSourceHandled,设置为true,代表执行完source后就会退出当前loop
//                CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e10, true);
//            }
            
            NSLog(@"end----");
        }];
        
        [self.innerThread start];
    }
    return self;
}

行者常至,为者常成!





R
Valine - A simple comment system based on Leancloud.