ios

来源:互联网 发布:死性不改网络歌手歌词 编辑:程序博客网 时间:2024/06/04 19:56

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
原创粉丝点击