您的位置:首页 > 理论基础 > 计算机网络

第01天多线程网络:(07):NSThread创建线程的生命周期

2017-04-15 00:00 309 查看
#####一、NSThread创建线程的生命周期

线程的生命周期:
当任务执行完毕之后被释放掉


code
LYHThread(写一个
继承NSThread的类
,调用
dealloc
方法就
能查看什么时候被销毁的
了)

#import <Foundation/Foundation.h>
@interface LYHThread : NSThread
@end
----
#import "LYHThread.h"
@implementation LYHThread
- (void)dealloc
{
NSLog(@"%s -- %@",__func__,[NSThread currentThread]);
}
@end

ViewController

/*
线程的生命周期:
当任务执行完毕之后被释放掉
*/

#import "ViewController.h"
#import "LYHThread.h"

#import <pthread.h>
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
#pragma 1.NSThread
[self createNewThread1];

}
#pragma 方式1 通过 - (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(id)argument; 创建子线程是属于一个休眠的状态的
- (void)createNewThread1
{
//1.创建线程,并且执行那个方法

LYHThread *threadA = [[LYHThread alloc]initWithTarget:self selector:@selector(run:) object:@"abc"];
// 设置属性
threadA.name = @"线程A"; // 线程名称
// 设置优先级 取值范围0.0 ~ 1.0 之间 最高是1.0 默认优先级是0.5
threadA.threadPriority = 1.0;
//2.执行线程
[threadA start];

}

- (void)run:(NSString *)parma
{
for (int i = 0; i<10000; i++) {
NSLog(@"%zd --- %@",i,[NSThread currentThread]);
}
}

void * _Nullable task(void * param)
{
// 把耗时操作放到子线程
for (int i = 0; i<10000; i++) {
NSLog(@"%zd --- %@",i,[NSThread currentThread]);
}

// 返回一个null
NSLog(@"__ %@",[NSThread currentThread]); // <NSThread: 0x61000006b900>{number = 3, name = (null)}
// number 不等于1 就是子线程
return NULL;
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息