#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