1.创建子线程并开启线程
2.给当前runloop添加port并运行runloop
3.将新任务添加到已休眠的线程
- (void)viewDidLoad {
[super viewDidLoad];
// 1.创建子线程并开启线程
NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
thread.name = @"myThread";
[thread start];
self.thread = thread;
}
- (void)run {
NSLog(@"----------run----%@", [NSThread currentThread]);
// 2.给当前runloop添加port并运行runloop
NSRunLoop *cuttentRunLoop = [NSRunLoop currentRunLoop];
[cuttentRunLoop addPort:[NSPort port] forMode:NSRunLoopCommonModes];
[cuttentRunLoop run];
//后面的都不是self.thread线程的事情 所以没有被打印 因为不会走到这一步 上面的一直在跑圈监听self.thread的线程
NSLog(@"----------我没有被打印---------");
}
//当外界给这个正在RunLoo的线程一个外力时,也能够发送消息给test。因为self.thread线程没有消亡(RunLoop即使休眠了也会因为self.thread里有mode而不会消亡)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//selector也是一个source
[self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO];
}
- (void)test
{
NSLog(@"----------test----%@", [NSThread currentThread]);
}