ios - 多线程之三:NSThread

NSThread 线程解决方案是经过苹果封装后的,并且是完全面向对象的,基于此呢,我们就可以直接来操作线程对象,比较直观。

思路

在viewController中添加一个按钮,点击按钮执行 NSThread 线程管理。

代码演示

1:创建按钮

  //第二种方式 NSThread

  UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];

btn1.frame = CGRectMake(40, 150, 100, 40);

[btn1 setTitle:@"NSThread" forState:UIControlStateNormal];

[btn1 setBackgroundColor:[UIColor blueColor]];

[btn1 addTarget:self action:@selector(click_NSThread) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:btn1];

2:定义点击事件

知识点:
- 初始化方法(有三种):
1:alloc - init 方法,使用该方法创建的线程需要手动开启线程 start。
2:类方法,静态方法:detachNewThreadSelector 创建并且执行
3:NSObject的内置方法:performSelectorInBackground,当然NSObject还有其他进行切换的方法:performSelectorOnMainThread(回到主线程中执行)performSelector:<@selector> onThread: ,

三种方式的优缺点对比

方式优点缺点
alloc - init 方法有自己的对象,可管理;可以设置线程名称,方便线程追踪;需要调用start才能够执行
静态方法没有线程对象;无需编写执行语句无法设置线程名称;无法设置线程优先级;
NSObject的内置方法没有线程对象;无需编写执行语句无法设置线程名称;无法设置线程优先级;

- 线程名称:类似ID,可在程序的调试过程中发挥很大作用;
- 线程优先级;大部分的理解还是我如果优先级大,就一定会先执行完,这个是一种误读,设置优先级大在多线程的世界里只能是表示优先级大的任务执行的概率相对大点。

代码:
- (void) click_NSThread {
NSLog(@”主线程打印”);
// 2 : NSThread 多线程
// 初始化方法一 : alloc - init 方法,使用该方法创建的线程需要手动开启线程start
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(runThread1) object:nil];
thread1.name = @”first_NSThread”; //设置线程的名称
thread1.threadPriority = 1; //设置线程的执行优先级

 //初始化方法二 : NSThread类方法创建, 不能指定线程名称和优先级
//    [NSThread detachNewThreadSelector:@selector(runThread1) toTarget:self withObject:nil];

//初始化方法三 : NSObject的内置方法,不能指定线程名称和优先级
//    [self performSelectorInBackground:@selector(runThread1) withObject:nil];


//设置线程的优先级
NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(runThread1) object:nil];
thread2.name = @"second_NSThread";
thread2.threadPriority = 0.5;


    NSThread *thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(runThread1) object:nil];
    thread3.name = @"third_NSThread";
    thread3.threadPriority = 0.2;

  [thread1 start]; //手动开启线程
  [thread2 start];
  [thread3 start];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值