您的位置:首页 > 大数据 > 人工智能

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

2016-10-09 20:33 316 查看
#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: