一、NSThread介绍
NSThread是基于线程使用,轻量级的多线程编程方法(相对GCD和NSOperation),一个NSThread对象代表一个线程,需要手动管理线程的生命周期,处理线程同步等问题。
注:NSThread经常用到的方法
[NSThread currentThread];//获取当前线程
二、使用
//1.动态实例化
//参数 2.执行方法 3.传递参数
NSThread *newThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadRun:) object:@"动态创建"];
//手动开启
[newThread start];
//2.静态实例化
//参数:1.执行方法 2.传递参数
[NSThread detachNewThreadSelector:@selector(threadRun:) toTarget:self withObject:@"测试"];
//3.隐式实例化
[self performSelectorInBackground:@selector(threadRun:) withObject:nil];
子线程执行方法
- (void)threadRun:(NSString *)str{
//当前线程[NSThread currentThread],主线程[NSThread mainThread]
NSLog(@"%s---%@---%@---%@",__FUNCTION__,[NSThread currentThread],str,[NSThread mainThread]);
}
暂停当前线程
[NSThread sleepForTimeInterval:2];
线程直接通信
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"%s---%@",__FUNCTION__,[NSThread currentThread]);
// 参数 2.执行方法 3.传递参数
NSThread *newThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadRun:) object:@"动态创建"];
//手动开启
[newThread start];
//waitUntilDone 是否等待 @selector 里面的方法执行完 再继续走下去
//在主线程上执行操作
[self performSelectorOnMainThread:@selector(threadMainRhread) withObject:nil waitUntilDone:YES];
//在当前线程执行操作
[self performSelector:@selector(threadcurrentThread) withObject:nil];
}
- (void)threadRun:(NSString *)str{
//当前线程,主线程
NSLog(@"%s---%@---%@---%@",__FUNCTION__,[NSThread currentThread],str,[NSThread mainThread]);
//在指定线程上执行操作
[self performSelector:@selector(threadNewThread) onThread:[NSThread currentThread] withObject:nil waitUntilDone:YES];
}
- (void)threadNewThread{
NSLog(@"%s---%@",__FUNCTION__,[NSThread currentThread]);
}
- (void)threadMainRhread{
NSLog(@"%s---%@",__FUNCTION__,[NSThread currentThread]);
}
- (void)threadcurrentThread{
NSLog(@"%s---%@",__FUNCTION__,[NSThread currentThread]);
}
@end
网友评论