/** run<NSThread: 0x712d5b0>{name = (null), num = 1}
num 为1 是主线程 其他就是创建的子线程
使用NSThread 的优缺点
1 优点:NSThread 比其他多线程方案较轻量级,更直观地控制线程对象
2 缺点:需要管理线程生命周期,同步加锁问题,会导致一定的性能开销
*/
- (void)viewDidLoad
{
[super viewDidLoad];
//创建线程方式
// NSThread *thread = [NSThread currentThread];
// NSThread *thread = [NSThread mainThread];
[self currentThread6];
}
//在当前线程中执行创建线程
- (void)currentThread6
{
[self performSelector:@selector(run) withObject:nil];
}
//主线程创建了一条线程
- (void)currentThread5
{
[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];
}
//指定的线程创建了一条线程
- (void)currentThread4
{
NSThread *thread = [NSThread mainThread];
[self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];
}
//隐士创建一条线程
- (void)currentThread3
{
//在后台运行调用创建线程
[self performSelectorInBackground:@selector(run) withObject:nil];
}
//执行完方法后启动一条新线程 静态方法 detachNewThreadSelector 没有返回值所以不需要启动线程
- (void)currentThread2
{
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
//线程延迟2秒调用当前主线程
// [NSThread sleepForTimeInterval:2];
//根据当前的时间停止2秒
NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]];
[NSThread sleepUntilDate:date];
NSLog(@"currentThread2");
}
//执行完方法后启动一条新线程 动态方法 initWithTarget 需要启动线程
- (void)currentThread1
{
//创建线程 调用线程方法
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
NSLog(@"viewDidLoad%@",thread);
//开启线程
[thread start];
}
//线程
- (void)run
{
//创建了一条线程
NSThread *thread = [NSThread currentThread];
NSLog(@"run%@",thread);
}