如何创建常驻线程以及waitUntilDone参数的作用


#import "ViewController.h"


@interface ViewController ()


@property (nonatomic, strong)NSThread *thread;


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

    [self createThread];

}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    // waitUntilDone设置为YES,会阻塞主线程,优先在子线程中执行task2方法,task2方法执行完后主线程再继续后面的打印

    // waitUntilDone设置为NO,子线程的task2方法和主线程的打印同时进行

    [self performSelector:@selector(task2) onThread:self.thread withObject:nil

            waitUntilDone:YES];

    

    NSLog(@"cukiy1--%@",[NSThread currentThread]);

    NSLog(@"cukiy2--%@",[NSThread currentThread]);

    NSLog(@"cukiy3--%@",[NSThread currentThread]);

    NSLog(@"cukiy4--%@",[NSThread currentThread]);

    NSLog(@"cukiy5--%@",[NSThread currentThread]);

    NSLog(@"----------");

}



- (void)createThread

{

    // 创建子线程执行任务

    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(task1) object:nil];

    [thread start];

    

    self.thread = thread;

}


- (void)task1

{

    NSLog(@"task1--%@",[NSThread currentThread]);

    

    // 子线程对应的runloop需要自己创建并开启

    // 创建子线程对应的runloop,使子线程一直存在

    NSRunLoop *currentRunloop = [NSRunLoop currentRunLoop];

    // runloop添加一个基于port的事件(系统事件),runloop的运行模式不为空,保证runloop不退出

    [currentRunloop addPort:[NSPort port] forMode:NSDefaultRunLoopMode];

    // 开启运行循环

    [currentRunloop run];

}


- (void)task2

{

//    sleep(3);

    NSLog(@"task2-1-%@",[NSThread currentThread]);

    NSLog(@"task2-2-%@",[NSThread currentThread]);

    NSLog(@"task2-3-%@",[NSThread currentThread]);

    NSLog(@"task2-4-%@",[NSThread currentThread]);

}


@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值