1.創(chuàng)建子線程并開啟線程
2.給當前runloop添加port并運行runloop
3.將新任務添加到已休眠的線程
- (void)viewDidLoad {
[super viewDidLoad];
// 1.創(chuàng)建子線程并開啟線程
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線程的事情 所以沒有被打印 因為不會走到這一步 上面的一直在跑圈監(jiān)聽self.thread的線程
NSLog(@"----------我沒有被打印---------");
}
//當外界給這個正在RunLoo的線程一個外力時,也能夠發(fā)送消息給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]);
}