iOS多线程 - NSTread详解

2020-02-21  本文已影响0人  凉秋落尘

前言

首先比较一下NSTread 和GCD,NSOperation三者之间的优缺点:

NSTread的使用

线程基本创建

1.
//   初始化线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(timeSel) object:nil];  
// 设置线程的优先级(0.0 - 1.0,1.0最高级)  
thread.threadPriority = 1;  
// 开启线程  
[thread start];

// 另一种新建线程,调用@selector方法 
[NSThread detachNewThreadSelector:@selector(timeSel) toTarget:self withObject:nil];

// 获取当前线程
NSThread *currentThread = [NSThread currentThread];
// 获取主线程
NSThread *mainThread = [NSThread mainThread];  

// 暂停7s  
[NSThread sleepForTimeInterval:7];  

// 或者  
NSDate *dateTime = [NSDate dateWithTimeInterval:7 sinceDate:[NSDate date]];  
[NSThread sleepUntilDate:dateTime]; //睡眠,直到时间dateTime线程继续进行操作

线程间通讯,常用方法performSelector

//在当前线程。延迟执行。
[self performSelector:@selector(test) withObject:nil afterDelay:1];
// 回到主线程。
// waitUntilDone(阻塞当前的线程):如果为YES,就必须等回调方法执行完成之后才能执行后面的代码;
// 如果是NO:就是不等回调方法结束,不会阻塞当前线程
[self performSelectorOnMainThread:@selector(test) withObject:nil waitUntilDone:YES];
//开辟子线程
[self performSelectorInBackground:@selector(test) withObject:nil];
//在指定线程执行
[self performSelector:@selector(test) onThread:[NSThread currentThread] withObject:nil waitUntilDone:YES]

需要注意的是:如果是带afterDelay的延时函数,会在内部创建一个 NSTimer,然后添加到当前线程的Runloop中。也就是如果当前线程没有开启runloop,该方法会失效。在子线程中,需要启动runloop(注意调用顺序)

[self performSelector:@selector(test) withObject:nil afterDelay:1];
[[NSRunLoop currentRunLoop] run];
上一篇 下一篇

猜你喜欢

热点阅读